Skip to content

Commit eff8f15

Browse files
committed
fix(platform-express) respect existing parser middlewares when using Express 5
Express 5 made the router public API again and renamed the field from app._router to app.router. This broke the detection mechanism whether a middleware named "jsonParser" or "urlencodedParser" is already registered or not. Unfortunately, #14574 only fixed the issue partially. This commit now uses app.router everywhere. To avoid future regressions a test was added to verify the expected behavior.
1 parent cda26df commit eff8f15

File tree

2 files changed

+47
-1
lines changed

2 files changed

+47
-1
lines changed

packages/platform-express/adapters/express-adapter.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -470,7 +470,7 @@ export class ExpressAdapter extends AbstractHttpAdapter<
470470
private isMiddlewareApplied(name: string): boolean {
471471
const app = this.getInstance();
472472
return (
473-
!!app._router &&
473+
!!app.router &&
474474
!!app.router.stack &&
475475
isFunction(app.router.stack.filter) &&
476476
app.router.stack.some(
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
import { ExpressAdapter } from '@nestjs/platform-express';
2+
import { expect } from 'chai';
3+
import * as express from 'express';
4+
import * as sinon from 'sinon';
5+
6+
afterEach(() => sinon.restore());
7+
8+
describe.only('ExpressAdapter', () => {
9+
describe('registerParserMiddleware', () => {
10+
it('should register the express built-in parsers for json and urlencoded payloads', () => {
11+
const expressInstance = express();
12+
const jsonParserInstance = express.json();
13+
const urlencodedInstance = express.urlencoded();
14+
const jsonParserSpy = sinon
15+
.stub(express, 'json')
16+
.returns(jsonParserInstance);
17+
const urlencodedParserSpy = sinon
18+
.stub(express, 'urlencoded')
19+
.returns(urlencodedInstance);
20+
const useSpy = sinon.spy(expressInstance, 'use');
21+
const expressAdapter = new ExpressAdapter(expressInstance);
22+
23+
expressAdapter.registerParserMiddleware();
24+
25+
expect(useSpy.calledTwice).to.be.true;
26+
expect(useSpy.calledWith(sinon.match.same(jsonParserInstance))).to.be
27+
.true;
28+
expect(useSpy.calledWith(sinon.match.same(urlencodedInstance))).to.be
29+
.true;
30+
expect(jsonParserSpy.calledOnceWith({})).to.be.true;
31+
expect(urlencodedParserSpy.calledOnceWith({ extended: true })).to.be.true;
32+
});
33+
34+
it('should not register default parsers if custom parsers have already been registered', () => {
35+
const expressInstance = express();
36+
expressInstance.use(function jsonParser() {});
37+
expressInstance.use(function urlencodedParser() {});
38+
const useSpy = sinon.spy(expressInstance, 'use');
39+
const expressAdapter = new ExpressAdapter(expressInstance);
40+
41+
expressAdapter.registerParserMiddleware();
42+
43+
expect(useSpy.called).to.be.false;
44+
});
45+
});
46+
});

0 commit comments

Comments
 (0)