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
47 lines
1.1 KiB
TypeScript
47 lines
1.1 KiB
TypeScript
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
|
|
}
|