Self-hosted personal gallery application with online photo management and albums, supporting Live/Motion Photos, EXIF parsing, geolocation recognition, and an explore map.
TypeScript albumsexif-extractiongeocodinglive-photomotion-photophoto-galleryphoto-sharingwebgl-viewer
fix(settings): localize server-side social link validation errors
Ahmet Ömerc2ff1593dd46
diff --git a/apps/self-hosted/server/api/system/settings/batch.put.ts b/apps/self-hosted/server/api/system/settings/batch.put.tsindex 8139b27a..1fa44fc7 100644--- a/apps/self-hosted/server/api/system/settings/batch.put.ts+++ b/apps/self-hosted/server/api/system/settings/batch.put.ts@@ -6,6 +6,7 @@ import {} from '~~/server/services/settings/contants'import { settingsManager } from '~~/server/services/settings/settingsManager'import { useDB, tables, eq } from '~~/server/utils/db'+import { applySettingsBatch } from '~~/server/utils/settings-batch-error'/*** PUT /api/system/settings/batch@@ -48,9 +49,6 @@ export default eventHandler(async (event) => {)try {- let successCount = 0- const errors: Array<{ namespace: string; key: string; error: string }> = []-// 获取当前用户ID,如果用户不存在于数据库则返回nullconst db = useDB()const currentUser = session.user.id@@ -62,46 +60,17 @@ export default eventHandler(async (event) => {: nullconst updatedBy = currentUser ? currentUser.id : undefined- // 逐个更新设置- for (const update of body.updates) {- if (getHiddenSettingKeys(update.namespace).has(update.key)) {- errors.push({- namespace: update.namespace,- key: update.key,- error: 'Setting is not directly modifiable',- })- continue- }- try {- await settingsManager.set(+ return applySettingsBatch(body.updates, {+ isHidden: (update) =>+ getHiddenSettingKeys(update.namespace).has(update.key),+ set: (update) =>+ settingsManager.set(update.namespace,update.key,update.value,updatedBy,- )- successCount++- } catch (err) {- errors.push({- namespace: update.namespace,- key: update.key,- error: (err as Error).message,- })- }- }-- // 如果有错误,返回部分成功的响应- if (errors.length > 0) {- return {- success: false,- updated: successCount,- errors,- }- }-- return {- success: true,- updated: successCount,- }+ ),+ })} catch (error) {throw createError({statusCode: 400,diff --git a/apps/self-hosted/server/utils/settings-batch-error.ts b/apps/self-hosted/server/utils/settings-batch-error.tsnew file mode 100644index 00000000..b966d383--- /dev/null+++ b/apps/self-hosted/server/utils/settings-batch-error.ts@@ -0,0 +1,56 @@+import { SocialLinkError } from '@chronoframe/contracts/social-links'+import type {+ SettingsBatchFieldError,+ SettingsBatchResponse,+} from '@chronoframe/contracts/settings'++export function toSettingsBatchError(+ namespace: string,+ key: string,+ error: unknown,+): SettingsBatchFieldError {+ return {+ namespace,+ key,+ error: error instanceof Error ? error.message : String(error),+ ...(namespace === 'app' &&+ key === 'socialLinks' &&+ error instanceof SocialLinkError+ ? { code: error.code }+ : {}),+ }+}++export async function applySettingsBatch<+ T extends { namespace: string; key: string },+>(+ updates: readonly T[],+ handlers: {+ isHidden: (update: T) => boolean+ set: (update: T) => Promise<void>+ },+): Promise<SettingsBatchResponse> {+ let updated = 0+ const errors: SettingsBatchFieldError[] = []++ for (const update of updates) {+ if (handlers.isHidden(update)) {+ errors.push({+ namespace: update.namespace,+ key: update.key,+ error: 'Setting is not directly modifiable',+ })+ continue+ }+ try {+ await handlers.set(update)+ updated+++ } catch (error) {+ errors.push(toSettingsBatchError(update.namespace, update.key, error))+ }+ }++ return errors.length > 0+ ? { success: false, updated, errors }+ : { success: true, updated }+}diff --git a/packages/console/app/composables/useSettingsForm.ts b/packages/console/app/composables/useSettingsForm.tsindex e66e26dc..e7dce94c 100644--- a/packages/console/app/composables/useSettingsForm.ts+++ b/packages/console/app/composables/useSettingsForm.ts@@ -1,8 +1,13 @@import type { InjectionKey } from 'vue'import type {FieldDescriptor,+ SettingsBatchResponse,SettingsFieldsResponse,} from '@chronoframe/gallery/shared/types/settings'+import {+ isSocialLinkErrorCode,+ SocialLinkError,+} from '@chronoframe/contracts/social-links'export const settingsFieldCommitKey: InjectionKey<(fieldKey: string, value: any) => void@@ -104,14 +109,26 @@ export function useSettingsForm(namespace: string) {value,}))- const result = await consoleApi<{- success: boolean- errors?: Array<{ error: string }>- }>('/api/system/settings/batch', {- method: 'PUT',- body: { updates },- })+ const result = await consoleApi<SettingsBatchResponse>(+ '/api/system/settings/batch',+ {+ method: 'PUT',+ body: { updates },+ },+ )if (!result.success) {+ const socialFailure = result.errors.find(+ (item) => item.namespace === 'app' && item.key === 'socialLinks',+ )+ if (socialFailure) {+ if (isSocialLinkErrorCode(socialFailure.code)) {+ throw new SocialLinkError(+ socialFailure.code,+ t(`settings.app.socialLinks.${socialFailure.code}`),+ )+ }+ throw new Error(t('settings.form.saveFailed'))+ }throw new Error(result.errors?.map((item) => item.error).join('; ') ||t('settings.form.saveFailed'),diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.tsindex b2643459..72c41ec9 100644--- a/packages/contracts/src/settings.ts+++ b/packages/contracts/src/settings.ts@@ -1,4 +1,5 @@import type { StorageConfig } from './storage.ts'+import type { SocialLinkErrorCode } from './social-links.ts'export type SettingType = 'string' | 'number' | 'boolean' | 'json'export type SettingValue =@@ -117,6 +118,17 @@ export interface SettingsFieldsResponse {fields: FieldDescriptor[]}+export interface SettingsBatchFieldError {+ namespace: string+ key: string+ error: string+ code?: SocialLinkErrorCode+}++export type SettingsBatchResponse =+ | { success: true; updated: number }+ | { success: false; updated: number; errors: SettingsBatchFieldError[] }+/*** Settings 批量更新请求*/diff --git a/packages/contracts/src/social-links.ts b/packages/contracts/src/social-links.tsindex 0e51ef1d..2d9527f4 100644--- a/packages/contracts/src/social-links.ts+++ b/packages/contracts/src/social-links.ts@@ -4,6 +4,17 @@ export const MAX_SOCIAL_LINKS = 4export type SocialLinkErrorCode = 'shape' | 'limit' | 'invalid' | 'duplicate'+export function isSocialLinkErrorCode(+ value: unknown,+): value is SocialLinkErrorCode {+ return (+ value === 'shape' ||+ value === 'limit' ||+ value === 'invalid' ||+ value === 'duplicate'+ )+}+export class SocialLinkError extends Error {readonly code: SocialLinkErrorCodediff --git a/tests/settings-batch-errors.test.ts b/tests/settings-batch-errors.test.tsnew file mode 100644index 00000000..da8642b4--- /dev/null+++ b/tests/settings-batch-errors.test.ts@@ -0,0 +1,124 @@+import assert from 'node:assert/strict'+import test from 'node:test'+import { reactive, readonly, ref } from 'vue'+import { SocialLinkError } from '@chronoframe/contracts/social-links'+import {+ applySettingsBatch,+ toSettingsBatchError,+} from '../apps/self-hosted/server/utils/settings-batch-error.ts'+import { useSettingsForm } from '../packages/console/app/composables/useSettingsForm.ts'++test('batch errors preserve social validation codes without coding unrelated failures', () => {+ assert.deepEqual(+ toSettingsBatchError(+ 'app',+ 'socialLinks',+ new SocialLinkError('limit', 'Use at most four social links'),+ ),+ {+ namespace: 'app',+ key: 'socialLinks',+ error: 'Use at most four social links',+ code: 'limit',+ },+ )+ assert.deepEqual(+ toSettingsBatchError('app', 'title', new Error('Write failed')),+ { namespace: 'app', key: 'title', error: 'Write failed' },+ )+})++test('batch response retains a social error code alongside successful updates', async () => {+ const result = await applySettingsBatch(+ [+ { namespace: 'app', key: 'title', value: 'Saved name' },+ { namespace: 'app', key: 'socialLinks', value: { links: [] } },+ ],+ {+ isHidden: () => false,+ set: async (update) => {+ if (update.key === 'socialLinks') {+ throw new SocialLinkError('duplicate', 'Duplicate social link')+ }+ },+ },+ )++ assert.deepEqual(result, {+ success: false,+ updated: 1,+ errors: [+ {+ namespace: 'app',+ key: 'socialLinks',+ error: 'Duplicate social link',+ code: 'duplicate',+ },+ ],+ })+})++test('social validation errors from batch save use localized inline and toast messages', async () => {+ const globals = globalThis as unknown as Record<string, unknown>+ const toasts: Array<{ description?: string }> = []+ let errorCode = 'limit'+ const overrides = {+ ref,+ reactive,+ readonly,+ onMounted: () => {},+ useConsoleApi: () => async (path: string) =>+ path.endsWith('/fields')+ ? { fields: [] }+ : {+ success: false,+ updated: 0,+ errors: [+ {+ namespace: 'app',+ key: 'socialLinks',+ error: 'Use at most four social links',+ code: errorCode,+ },+ ],+ },+ useI18n: () => ({+ t: (key: string) =>+ key === 'settings.app.socialLinks.limit'+ ? 'Add no more than four links'+ : key === 'settings.form.saveFailed'+ ? 'Could not save settings'+ : key,+ }),+ useToast: () => ({+ add: (toast: { description?: string }) => toasts.push(toast),+ }),+ refreshSettings: async () => {},+ }+ const previous = Object.fromEntries(+ Object.keys(overrides).map((key) => [key, globals[key]]),+ )+ Object.assign(globals, overrides)+ try {+ const form = useSettingsForm('app')+ await assert.rejects(+ form.submit({ socialLinks: { links: [] } }),+ (error: unknown) =>+ error instanceof SocialLinkError &&+ error.code === 'limit' &&+ error.message === 'Add no more than four links',+ )+ assert.equal(toasts.at(-1)?.description, 'Add no more than four links')++ errorCode = 'new-server-code'+ await assert.rejects(form.submit({ socialLinks: { links: [] } }), {+ message: 'Could not save settings',+ })+ assert.equal(toasts.at(-1)?.description, 'Could not save settings')+ } finally {+ for (const [key, value] of Object.entries(previous)) {+ if (value === undefined) delete globals[key]+ else globals[key] = value+ }+ }+})