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