refactor: centralize validation, error handling, and formatting logic

Extract shared auth logic and validation rules to shared/auth.ts
Introduce utility functions for HTTP errors and user input parsing
Standardize error messages and date formatting across the app
This commit is contained in:
2026-04-12 20:29:39 +08:00
parent 377a9617be
commit 07e5d42005
23 changed files with 294 additions and 267 deletions

View File

@@ -1,14 +1,10 @@
import {
DEFAULT_USER_PASSWORD,
USERNAME_PATTERN,
isValidPhoneNumber,
normalizePhoneNumber,
type UserRole
} from '~~/shared/auth'
import { DEFAULT_USER_PASSWORD, type UserRole } from '~~/shared/auth'
import { normalizeUsername, requireRole } from '../../utils/auth'
import { requireRole } from '../../utils/auth'
import { mapDatabaseError } from '../../utils/http'
import { hashPassword } from '../../utils/password'
import { createUser } from '../../utils/user-repository'
import { parseCreateUserInput } from '../../utils/users'
export default defineEventHandler(async (event) => {
const auth = await requireRole(event, 'super_admin')
@@ -19,31 +15,12 @@ export default defineEventHandler(async (event) => {
role?: UserRole
}>(event)
const username = normalizeUsername(body.username || '')
const fullName = body.fullName?.trim() || ''
const phoneNumber = normalizePhoneNumber(body.phoneNumber || '')
const role = body.role === 'super_admin' ? 'super_admin' : 'staff'
if (!USERNAME_PATTERN.test(username)) {
throw createError({
statusCode: 400,
statusMessage: 'Username must be 3 to 32 characters using lowercase letters, numbers, dot, dash, or underscore'
})
}
if (fullName.length < 2) {
throw createError({
statusCode: 400,
statusMessage: 'Full name must be at least 2 characters'
})
}
if (!isValidPhoneNumber(phoneNumber)) {
throw createError({
statusCode: 400,
statusMessage: 'Phone number must contain 8 to 15 digits'
})
}
const {
username,
fullName,
phoneNumber,
role
} = parseCreateUserInput(body)
const passwordHash = await hashPassword(DEFAULT_USER_PASSWORD)
@@ -61,14 +38,12 @@ export default defineEventHandler(async (event) => {
user,
defaultPassword: DEFAULT_USER_PASSWORD
}
} catch (error: any) {
if (error?.code === '23505') {
throw createError({
} catch (error) {
mapDatabaseError(error, {
'23505': {
statusCode: 409,
statusMessage: 'Username already exists'
})
}
throw error
}
})
}
})