feat: major code refactor, add login and register endpoints with swagger
All checks were successful
Update changelog / changelog (push) Successful in 27s
All checks were successful
Update changelog / changelog (push) Successful in 27s
This commit is contained in:
40
src/tools/validateSchema.ts
Normal file
40
src/tools/validateSchema.ts
Normal file
@@ -0,0 +1,40 @@
|
||||
// Heavily based on:
|
||||
// https://github.com/TomDoesTech/REST-API-Tutorial-Updated/blob/7b5f040e1acd94d267df585516b33ee7e3b75f70/src/middleware/validateResource.ts
|
||||
import { Request, Response, NextFunction } from 'express';
|
||||
import { ErrorDTO } from '../schemas/miscSchema';
|
||||
import z from 'zod';
|
||||
|
||||
const validate =
|
||||
(schema: z.ZodObject) =>
|
||||
(req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
schema.parse({
|
||||
body: req.body,
|
||||
query: req.query,
|
||||
params: req.params,
|
||||
});
|
||||
next();
|
||||
} catch (e: any) {
|
||||
if (e instanceof z.ZodError) {
|
||||
let errorResponse: ErrorDTO = {
|
||||
status: 'error',
|
||||
error: e.issues[0]?.message ?? 'Unknown error',
|
||||
code: e.issues[0]?.code
|
||||
};
|
||||
return res.status(400)
|
||||
.json(errorResponse);
|
||||
} else {
|
||||
console.log('Generic error triggered:', e);
|
||||
let errorResponse: ErrorDTO = {
|
||||
status: 'error',
|
||||
error: 'Unknown error',
|
||||
code: 'generic-error'
|
||||
};
|
||||
return res.status(400)
|
||||
.json(errorResponse);
|
||||
}
|
||||
|
||||
}
|
||||
};
|
||||
|
||||
export default validate;
|
||||
Reference in New Issue
Block a user