Public Access
- Created adminApi.ts for admin-related operations including user management and site settings. - Developed authApi.ts for authentication processes such as registration, login, and profile management. - Added examApi.ts for handling exam CRUD operations. - Introduced resultApi.ts for managing results submission and retrieval. - Established setupApi.ts for initial setup processes and status checks. - Created ErrorBoundary component to handle rendering errors gracefully in the frontend. - Re-exported shared API utilities in index.ts for easier access.
44 lines
1.3 KiB
TypeScript
44 lines
1.3 KiB
TypeScript
import { z } from 'zod'
|
|
import type { Request, Response, NextFunction } from 'express'
|
|
|
|
function getFirstIssueMessage(error: z.ZodError): string {
|
|
const issue = error.issues[0]
|
|
return issue?.message ?? 'Validation failed'
|
|
}
|
|
|
|
export function validateBody<T extends z.ZodTypeAny>(schema: T) {
|
|
return (req: Request, res: Response, next: NextFunction): void => {
|
|
const result = schema.safeParse(req.body)
|
|
if (!result.success) {
|
|
res.status(400).json({ error: getFirstIssueMessage(result.error) })
|
|
return
|
|
}
|
|
req.body = result.data as z.infer<T>
|
|
next()
|
|
}
|
|
}
|
|
|
|
export function validateQuery<T extends z.ZodTypeAny>(schema: T) {
|
|
return (req: Request, res: Response, next: NextFunction): void => {
|
|
const result = schema.safeParse(req.query)
|
|
if (!result.success) {
|
|
res.status(400).json({ error: getFirstIssueMessage(result.error) })
|
|
return
|
|
}
|
|
;(req as unknown as Record<string, unknown>).parsedQuery = result.data
|
|
next()
|
|
}
|
|
}
|
|
|
|
export function validateParams<T extends z.ZodTypeAny>(schema: T) {
|
|
return (req: Request, res: Response, next: NextFunction): void => {
|
|
const result = schema.safeParse(req.params)
|
|
if (!result.success) {
|
|
res.status(400).json({ error: getFirstIssueMessage(result.error) })
|
|
return
|
|
}
|
|
Object.assign(req.params, result.data)
|
|
next()
|
|
}
|
|
}
|