Reputation: 1650
I'm building a very little rest api using nodejs, express and inversify.
Here it is my working code:
index.ts
const container = new Container();
container.bind<interfaces.Controller>(Types.Controller)
.to(MyController)
.whenTargetNamed(Targets.Controller.MyController);
container.bind<Types.Service>(Types.Service)
.to(MyService)
.whenTargetNamed(Targets.Services.MyService);
const server = new InversifyExpressServer(container);
const app = server.build();
app.listen(3000);
mycontroller.ts
@injectable()
@controller('/api/test')
export class MyController {
constructor(@inject(Types.Service)
@named(Targets.Service.MyService)
private MyService: MyService) { }
@httpGet('/')
public getCompanies(req: Request, res: Response, next: any): Promise<any[]>
{
console.log('getTestData');
return this.MyService.fetchAll();
}
}
The above code is working fine. The problem comes out when I want to use a middleware to check the auth token.
authmiddleware.ts
function authMiddlewareFactory(
{
return (config: { role: string }) =>
{
return (req: Request, res: Response, next: any): void =>
{
const token = getToken(req);
console.log(token);
if (token === null)
{
res.status(403).json({ err: 'You are not allowed' });
return;
}
next();
}
}
const authMiddleware = authMiddlewareFactory();
export { authMiddleware };
If I use directly the auth middleware directly in the controller I get the 'You are not allowed' message as expected:
mycontroller.ts
@httpGet('/')
public getCompanies(req: Request, res: Response, next: any): Promise<any[]>
{
authMiddleware({ role: "admin" })(req, res, next);
console.log('getCompanies');
return this.CompanyService.fetchAll();
}
But If I use inversify:
import { authMiddleware } from './authmiddleware'
@injectable()
@controller('/api/test', authMiddleware({ role: "admin" }))
export class MyController {
// same code as before
I got the following error in compilation time:
ERROR: No matching bindings found for serviceIdentifier:
Error: No matching bindings found for serviceIdentifier:
at InversifyExpressServer.resolveMidleware (node_modules/inversify-express-utils/lib/server.js:133:27) at InversifyExpressServer.registerControllers (inversify-express-utils/lib/server.js:106:21) at InversifyExpressServer.build (node_modules/inversify-express-utils/lib/server.js:94:14) at Object. (dist/index.js:52:20)
I assume that I've to declare my middleware in index.ts like I did for the controller and the service. I tried but without successed.
Thanks
Upvotes: 3
Views: 8622
Reputation: 24979
I'm using the following versions:
"inversify": "4.5.2",
"inversify-express-utils": "5.0.0",
"reflect-metadata": "0.1.10",
"chai": "4.0.2",
"@types/chai": "4.0.0",
"@types/supertest": "2.0.2 ",
"supertest": "3.0.0",
I wrote the following quick test:
import "reflect-metadata";
import * as express from "express";
import { expect } from "chai";
import { Container, injectable, inject, named } from "inversify";
import { InversifyExpressServer, interfaces, controller, httpGet } from "inversify-express-utils";
import * as request from "supertest";
interface IMyService {
fetchAll(): Promise<string[]>;
}
const Types = {
Service: Symbol.for("Service")
};
const Targets = {
Service: {
MyService: "MyService"
}
};
function authMiddlewareFactory() {
return (config: { role: string }) => {
return (req: express.Request, res: express.Response, next: express.NextFunction): void => {
const token = req.headers["x-auth-token"];
console.log(token);
if (token === null) {
res.status(403).json({ err: "You are not allowed" });
return;
}
next();
};
};
}
const authMiddleware = authMiddlewareFactory();
const container = new Container();
@injectable()
class MyService implements IMyService {
public fetchAll() {
return Promise.resolve(["Hello", "World"]);
}
}
@controller("/api/test")
export class MyController {
constructor(
@inject(Types.Service) @named(Targets.Service.MyService) private myService: MyService
) { }
@httpGet("/", authMiddleware({ role: "admin" }))
public async getCompanies(req: express.Request, res: express.Response, next: express.NextFunction): Promise<string[]> {
console.log("getTestData");
return await this.myService.fetchAll();
}
}
container.bind<MyService>(Types.Service)
.to(MyService)
.whenTargetNamed(Targets.Service.MyService);
const server = new InversifyExpressServer(container);
const app = server.build();
request(app)
.get("/api/test")
.set("x-auth-token", "Token 1234567890")
.expect("Content-Type", /json/)
.expect(200)
.expect(function(res: any) {
const b = res.body;
console.log(b);
expect(b[0]).eq("Hello");
expect(b[1]).eq("World");
})
.end(function(err, res) {
if (err) {
throw err;
}
});
It prints the following:
Token 1234567890
getTestData
[ 'Hello', 'World' ]
In inversify-express-utils
5.0.0 (the recommended version right now) you don't need to declare bindings for controllers and you also don't need to decorate controllers with @injectable()
.
I created my example using one unique file but in the real application, you will have multiple files. You need to import your controller one time:
import "./controllers/some_controller";
You can learn more about this at https://github.com/inversify/inversify-express-utils#important-information-about-the-controller-decorator and https://github.com/inversify/inversify-express-utils/releases/tag/5.0.0.
Upvotes: 5