From f44f5d7ac2d24ff836c2e1d4b2fa58da04b13052 Mon Sep 17 00:00:00 2001 From: Madeline <46743919+MaddyUnderStars@users.noreply.github.com> Date: Sun, 25 Sep 2022 18:24:21 +1000 Subject: Refactor to mono-repo + upgrade packages --- src/api/middlewares/BodyParser.ts | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 src/api/middlewares/BodyParser.ts (limited to 'src/api/middlewares/BodyParser.ts') diff --git a/src/api/middlewares/BodyParser.ts b/src/api/middlewares/BodyParser.ts new file mode 100644 index 00000000..4cb376bc --- /dev/null +++ b/src/api/middlewares/BodyParser.ts @@ -0,0 +1,19 @@ +import bodyParser, { OptionsJson } from "body-parser"; +import { NextFunction, Request, Response } from "express"; +import { HTTPError } from "lambert-server"; + +export function BodyParser(opts?: OptionsJson) { + const jsonParser = bodyParser.json(opts); + + return (req: Request, res: Response, next: NextFunction) => { + if (!req.headers["content-type"]) req.headers["content-type"] = "application/json"; + + jsonParser(req, res, (err) => { + if (err) { + // TODO: different errors for body parser (request size limit, wrong body type, invalid body, ...) + return next(new HTTPError("Invalid Body", 400)); + } + next(); + }); + }; +} -- cgit 1.5.1