Fix express body parsing middlewares corrupting AsyncLocalStorage

Closes #17
This commit is contained in:
Alice Gaudon 2021-01-24 16:35:33 +01:00
parent 1b8ff1428f
commit 19c8b86ff8
2 changed files with 18 additions and 5 deletions

View File

@ -25,3 +25,16 @@ export const loggingContextMiddleware: RequestHandler = (req, res, next) => {
next();
});
};
export const preventContextCorruptionMiddleware = (delegate: RequestHandler): RequestHandler => (
req,
res,
next,
) => {
const data = requestIdStorage.getStore() as string;
delegate(req, res, (err?: Error | 'router') => {
requestIdStorage.enterWith(data);
next(err);
});
};

View File

@ -1,6 +1,6 @@
import ApplicationComponent from "../ApplicationComponent";
import express, {Express, Router} from "express";
import {logger} from "../Logger";
import {logger, preventContextCorruptionMiddleware} from "../Logger";
import {Server} from "http";
import compression from "compression";
import Middleware from "../Middleware";
@ -30,12 +30,12 @@ export default class ExpressAppComponent extends ApplicationComponent {
}
public async init(router: Router): Promise<void> {
router.use(express.json({
router.use(preventContextCorruptionMiddleware(express.json({
type: req => req.headers['content-type']?.match(/^application\/(.+\+)?json$/),
}));
router.use(express.urlencoded({
})));
router.use(preventContextCorruptionMiddleware(express.urlencoded({
extended: true,
}));
})));
// gzip
router.use(compression());