diff --git a/src/utils/error.ts b/src/utils/error.ts index 076a457..af28e5a 100644 --- a/src/utils/error.ts +++ b/src/utils/error.ts @@ -1,4 +1,18 @@ -import {Response} from "express"; +import { Response } from 'express'; +import { ObjectSchema } from 'joi'; + +const codeMappings: Record = { + "any.required": 1, // TODO + "any": 0 +}; export const sendError = (res: Response, httpCode: number, errorCode: number, message: string, fieldName?: string) => - res.status(httpCode).json({code: errorCode, message, fieldName}); \ No newline at end of file + res.status(httpCode).json({ code: errorCode, message, fieldName }); + +export const validateSchema = (res: Response, schema: ObjectSchema, object: Record) => { + const { error } = schema.validate(object, { errors: { wrap: { label: '' } } }); + const errorCode: number = codeMappings[error?.details[0].type || 'any'] || 0; + const message: string = error?.details[0].message || 'No message provided'; + + sendError(res, 400, errorCode, message); +}; \ No newline at end of file