Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow middlewares to be auto bound #316

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -187,7 +187,9 @@ export class InversifyExpressServer {

private resolveMidleware(...middleware: interfaces.Middleware[]): express.RequestHandler[] {
return middleware.map(middlewareItem => {
if (!this._container.isBound(middlewareItem)) {
if (!this._container.options.autoBindInjectable
&& !this._container.isBound(middlewareItem)
|| !this._container.get(middlewareItem)) {
return middlewareItem as express.RequestHandler;
}

Expand Down
40 changes: 39 additions & 1 deletion test/base_middleware.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@ import {
httpGet,
BaseMiddleware,
BaseHttpController,
interfaces
interfaces,
response
} from "../src/index";
import { cleanUpMetadata } from "../src/utils";

Expand Down Expand Up @@ -291,6 +292,43 @@ describe("BaseMiddleware", () => {
});

});

it("Should resolve middlewares if autoBindInjectable is set to true", (done) => {

@injectable()
class AutoBoundMiddleware extends BaseMiddleware {

public handler(
req: express.Request,
res: express.Response,
next: express.NextFunction
) {
res.locals.value = "This was auto bound";
next();
}
}

@controller("/autobind")
class AutoBoundMiddlewareTestController extends BaseHttpController {

@httpGet(
"/",
AutoBoundMiddleware
)
public getTest(@response() res: express.Response) {
return res.locals.value;
}
}

const container = new Container({ autoBindInjectable: true });

const app = new InversifyExpressServer(container).build();

supertest(app)
.get("/autobind")
.expect(200, "This was auto bound", () => done());

});
});

function run(parallelRuns: number, test: (executionId: number) => PromiseLike<any>, done: (error?: Error) => void) {
Expand Down