Skip to content

Commit

Permalink
feat(core): middleware should run once for one request. (nestjs#1628)
Browse files Browse the repository at this point in the history
  • Loading branch information
2218301630@qq.com authored and 2218301630@qq.com committed Sep 24, 2019
1 parent 61992c7 commit 76230ed
Show file tree
Hide file tree
Showing 2 changed files with 78 additions and 1 deletion.
68 changes: 68 additions & 0 deletions integration/hello-world/e2e/middleware-execute-once.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import {
Controller,
Get,
INestApplication,
Injectable,
MiddlewareConsumer,
NestMiddleware,
Module,
} from '@nestjs/common';
import { Test } from '../../../packages/testing';
import * as request from 'supertest';
import { expect } from 'chai';

let number: number = 0;

@Injectable()
class Middleware implements NestMiddleware {
use(req, res, next) {
number++;
next();
}
}

@Controller('/a')
class TestController {
@Get('/test')
testA() {
return '';
}
@Get('/:id')
testB() {
return '';
}
}

@Module({
controllers: [TestController],
})
class TestModule {
configure(consumer: MiddlewareConsumer) {
consumer.apply(Middleware).forRoutes(TestController);
}
}

describe('Middleware (execution once)', () => {
let app: INestApplication;

beforeEach(async () => {
app = (await Test.createTestingModule({
imports: [TestModule],
}).compile()).createNestApplication();

await app.init();
});

it(`forRoutes(TestController) should execute middleware once`, () => {
return request(app.getHttpServer())
.get('/a/test')
.expect(200)
.then(() => {
expect(number).to.be.eq(1);
});
});

afterEach(async () => {
await app.close();
});
});
11 changes: 10 additions & 1 deletion packages/core/middleware/middleware-module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -256,7 +256,16 @@ export class MiddlewareModule {
undefined,
contextId,
);
const middleware = instance.use.bind(instance);
const middleware = (req, res, next) => {
const stack: Set<NestMiddleware> = req.stack || new Set();
if (!stack.has(instance)) {
stack.add(instance);
req.stack = stack;
instance.use.apply(instance, [req, res, next]);
} else {
next();
}
};
return this.routerProxy.createProxy(middleware, exceptionsHandler);
}

Expand Down

0 comments on commit 76230ed

Please sign in to comment.