-
Notifications
You must be signed in to change notification settings - Fork 8
/
helpers.ts
60 lines (51 loc) · 1.54 KB
/
helpers.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import { SchemaValidationError } from "slonik";
import { AnyZodObject, ZodError, z } from "zod";
import { Request, Response, NextFunction } from "express";
export function formatQueryErrorResponse(e: SchemaValidationError) {
return e.issues.map(issue => ` ${issue.path} - ${issue.code} - ${issue.message} ||`)
}
export function validateRequest<T extends AnyZodObject>(schema: T) {
return async (req: Request, res: Response, next: NextFunction) => {
try {
const result = await schema.parseAsync({
body: req.body,
query: req.query,
params: req.params,
});
req.validated = result
next();
} catch (error) {
if (error instanceof ZodError) {
const formattedError = _formatZodError(error)
console.log('ZodError: ', formattedError)
return badRequest(formattedError, res)
}
console.log('Validation Error: ', error)
return badRequest(JSON.stringify(error), res)
}
};
}
export function badRequest(message: string, res: Response) {
return res.status(422).json({ message });
}
export function filterNullValues(obj: Record<string, any>) {
return Object.fromEntries(
Object.entries(obj)
.filter(([_, v]) => v != null)
);
}
function _formatZodError(error: ZodError): string {
return error.errors
.map((issue) => `${issue.path.join('.')} - ${issue.message}`)
.join(' || ');
}
export const TEST_USER = {
userEmail: '[email protected]',
userFullName: 'Test User',
};
export class NotFoundError extends Error {
constructor(message: string = "Not Found") {
super(message);
this.name = 'NotFoundError';
}
}