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,22 +1,13 @@
import {
isValidPhoneNumber,
normalizePhoneNumber,
type UserRole
} from '~~/shared/auth'
import type { UserRole } from '~~/shared/auth'
import { requireRole } from '../../../utils/auth'
import { getUserById, updateUserProfile } from '../../../utils/user-repository'
import { updateUserProfile } from '../../../utils/user-repository'
import { httpError } from '../../../utils/http'
import { parseUserProfileInput, requireExistingUser, requireUserIdParam } from '../../../utils/users'
export default defineEventHandler(async (event) => {
const auth = await requireRole(event, 'super_admin')
const userId = getRouterParam(event, 'id')
if (!userId) {
throw createError({
statusCode: 400,
statusMessage: 'User id is required'
})
}
const userId = requireUserIdParam(event)
const body = await readBody<{
fullName?: string
@@ -24,45 +15,12 @@ export default defineEventHandler(async (event) => {
role?: UserRole
}>(event)
const fullName = body.fullName?.trim() || ''
const phoneNumber = normalizePhoneNumber(body.phoneNumber || '')
const role = body.role
const { fullName, phoneNumber, role } = parseUserProfileInput(body)
if (fullName.length < 2) {
throw createError({
statusCode: 400,
statusMessage: 'Display name must be at least 2 characters'
})
}
if (!isValidPhoneNumber(phoneNumber)) {
throw createError({
statusCode: 400,
statusMessage: 'Phone number must contain 8 to 15 digits'
})
}
if (role !== 'super_admin' && role !== 'staff') {
throw createError({
statusCode: 400,
statusMessage: 'Role is invalid'
})
}
const user = await getUserById(userId)
if (!user) {
throw createError({
statusCode: 404,
statusMessage: 'User not found'
})
}
await requireExistingUser(userId)
if (auth.user.id === userId && role !== 'super_admin') {
throw createError({
statusCode: 400,
statusMessage: 'You cannot remove your own super admin access'
})
httpError(400, 'You cannot remove your own super admin access')
}
const updatedUser = await updateUserProfile({