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:
46
server/utils/http.ts
Normal file
46
server/utils/http.ts
Normal file
@@ -0,0 +1,46 @@
|
||||
import type { H3Event } from 'h3'
|
||||
|
||||
import { getRouterParam } from 'h3'
|
||||
|
||||
export function httpError(statusCode: number, statusMessage: string): never {
|
||||
throw createError({
|
||||
statusCode,
|
||||
statusMessage
|
||||
})
|
||||
}
|
||||
|
||||
export function assertHttp(
|
||||
condition: unknown,
|
||||
statusCode: number,
|
||||
statusMessage: string
|
||||
): asserts condition {
|
||||
if (!condition) {
|
||||
httpError(statusCode, statusMessage)
|
||||
}
|
||||
}
|
||||
|
||||
export function assertBadRequest(condition: unknown, statusMessage: string): asserts condition {
|
||||
assertHttp(condition, 400, statusMessage)
|
||||
}
|
||||
|
||||
export function getRequiredRouteParam(event: H3Event, name: string, label = name) {
|
||||
const value = getRouterParam(event, name)
|
||||
|
||||
assertBadRequest(value, `${label} is required`)
|
||||
|
||||
return value
|
||||
}
|
||||
|
||||
export function mapDatabaseError(
|
||||
error: unknown,
|
||||
handlers: Partial<Record<string, { statusCode: number, statusMessage: string }>>
|
||||
): never {
|
||||
const code = (error as { code?: string } | null)?.code
|
||||
const handler = code ? handlers[code] : undefined
|
||||
|
||||
if (handler) {
|
||||
httpError(handler.statusCode, handler.statusMessage)
|
||||
}
|
||||
|
||||
throw error
|
||||
}
|
||||
Reference in New Issue
Block a user