Skip to content

Some utilities for the development of Express application with InversifyJS

License

Notifications You must be signed in to change notification settings

inversify/inversify-express-utils

Folders and files

NameName
Last commit message
Last commit date

Latest commit

inversify-express-utils

Note

Inversify express utils are deprecated. New http utils are part of the framework included in the monorepo.

Documentation pages are avaliable here

Join the chat at https://gitter.im/inversify/InversifyJSnpm versionKnown Vulnerabilities

NPMNPM

Some utilities for the development of express applications with Inversify.

Installation

You can install inversify-express-utils using npm:

npm install inversify inversify-express-utils reflect-metadata --save

The inversify-express-utils type definitions are included in the npm module and require TypeScript 2.0. Please refer to the InversifyJS documentation to learn more about the installation process.

The Basics

Step 1: Decorate your controllers

To use a class as a "controller" for your express app, simply add the @controller decorator to the class. Similarly, decorate methods of the class to serve as request handlers.

The following example will declare a controller that responds to `GET /foo'.

import*asexpressfrom"express";import{interfaces,controller,httpGet,httpPost,httpDelete,request,queryParam,response,requestParam}from"inversify-express-utils";import{injectable,inject}from"inversify"; @controller("/foo")exportclassFooControllerimplementsinterfaces.Controller{constructor( @inject("FooService")privatefooService: FooService){} @httpGet("/")privateindex(@request()req: express.Request, @response()res: express.Response, @next()next: express.NextFunction): string{returnthis.fooService.get(req.query.id);} @httpGet("/")privatelist(@queryParam("start")start: number, @queryParam("count")count: number): string{returnthis.fooService.get(start,count);} @httpPost("/")privateasynccreate(@request()req: express.Request, @response()res: express.Response){try{awaitthis.fooService.create(req.body);res.sendStatus(201);}catch(err){res.status(400).json({error: err.message});}} @httpDelete("/:id")privatedelete(@requestParam("id")id: string, @response()res: express.Response): Promise<void>{returnthis.fooService.delete(id).then(()=>res.sendStatus(204)).catch((err: Error)=>{res.status(400).json({error: err.message});});}}

Step 2: Configure container and server

Configure the inversify container in your composition root as usual.

Then, pass the container to the InversifyExpressServer constructor. This will allow it to register all controllers and their dependencies from your container and attach them to the express app. Then just call server.build() to prepare your app.

In order for the InversifyExpressServer to find your controllers, you must bind them to the TYPE.Controller service identifier and tag the binding with the controller's name. The Controller interface exported by inversify-express-utils is empty and solely for convenience, so feel free to implement your own if you want.

import*asbodyParserfrom'body-parser';import{Container}from'inversify';import{interfaces,InversifyExpressServer,TYPE}from'inversify-express-utils';// declare metadata by @controller annotationimport"./controllers/foo_controller";// set up containerletcontainer=newContainer();// set up bindingscontainer.bind<FooService>('FooService').to(FooService);// create serverletserver=newInversifyExpressServer(container);server.setConfig((app)=>{// add body parserapp.use(bodyParser.urlencoded({extended: true}));app.use(bodyParser.json());});letapp=server.build();app.listen(3000);

Important information about the @controller decorator

Since the [email protected] release. The @injectable annotation is no longer required in classes annotated with @controller. Declaring a type binding for controllers is also no longer required in classes annotated with @controller.

⚠️ Declaring a binding is not required for Controllers but it is required to import the controller one unique time. When the controller file is imported (e.g. import "./controllers/some_controller") the class is declared and the metadata is generated. If you don't import it the metadata is never generated and therefore the controller is not found. An example of this can be found here.

If you run the application multiple times within a shared runtime process (e.g. unit testing) you might need to clean up the existing metadata before each test.

import{cleanUpMetadata}from"inversify-express-utils";describe("Some Component",()=>{beforeEach(()=>{cleanUpMetadata();});it("Some test case",()=>{// ...});});

You can find an example of this in our unit tests.

Inversify express utils will throw an exception if your application doesn't have controllers. You can disable this behaviour using the forceControllers option. You can find some examples of forceControllers in our unit tests.

InversifyExpressServer

A wrapper for an express Application.

.setConfig(configFn)

Optional - exposes the express application object for convenient loading of server-level middleware.

import*asmorganfrom'morgan';// ...letserver=newInversifyExpressServer(container);server.setConfig((app)=>{varlogger=morgan('combined')app.use(logger);});

.setErrorConfig(errorConfigFn)

Optional - like .setConfig(), except this function is applied after registering all app middleware and controller routes.

letserver=newInversifyExpressServer(container);server.setErrorConfig((app)=>{app.use((err,req,res,next)=>{console.error(err.stack);res.status(500).send('Something broke!');});});

.build()

Attaches all registered controllers and middleware to the express application. Returns the application instance.

// ...letserver=newInversifyExpressServer(container);server.setConfig(configFn).setErrorConfig(errorConfigFn).build().listen(3000,'localhost',callback);

Using a custom Router

It is possible to pass a custom Router instance to InversifyExpressServer:

letcontainer=newContainer();letrouter=express.Router({caseSensitive: false,mergeParams: false,strict: false});letserver=newInversifyExpressServer(container,router);

By default server will serve the API at / path, but sometimes you might need to use different root namespace, for example all routes should start with /api/v1. It is possible to pass this setting via routing configuration to InversifyExpressServer

letcontainer=newContainer();letserver=newInversifyExpressServer(container,null,{rootPath: "/api/v1"});

Using a custom express application

It is possible to pass a custom express.Application instance to InversifyExpressServer:

letcontainer=newContainer();letapp=express();//Do stuff with appletserver=newInversifyExpressServer(container,null,null,app);

Decorators

@controller(path, [middleware, ...])

Registers the decorated class as a controller with a root path, and optionally registers any global middleware for this controller.

@httpMethod(method, path, [middleware, ...])

Registers the decorated controller method as a request handler for a particular path and method, where the method name is a valid express routing method.

@SHORTCUT(path, [middleware, ...])

Shortcut decorators which are simply wrappers for @httpMethod. Right now these include @httpGet, @httpPost, @httpPut, @httpPatch, @httpHead, @httpDelete, @httpOptions, and @All. For anything more obscure, use @httpMethod (Or make a PR 😄).

@request()

Binds a method parameter to the request object.

@response()

Binds a method parameter to the response object.

@requestParam(name: string)

Binds a method parameter to request.params object or to a specific parameter if a name is passed.

@queryParam(name: string)

Binds a method parameter to request.query or to a specific query parameter if a name is passed.

@requestBody()

Binds a method parameter to the request.body. If the bodyParser middleware is not used on the express app, this will bind the method parameter to the express request object.

@requestHeaders(name: string)

Binds a method parameter to the request headers.

@cookies(name: string)

Binds a method parameter to the request cookies.

@next()

Binds a method parameter to the next() function.

@principal()

Binds a method parameter to the user principal obtained from the AuthProvider.

BaseHttpController

The BaseHttpController is a base class that provides a significant amount of helper functions in order to aid writing testable controllers. When returning a response from a method defined on one of these controllers, you may use the response object available on the httpContext property described in the next section, or you may return an HttpResponseMessage, or you may return an object that implements the IHttpActionResult interface.

The benefit of the latter two methods is that since your controller is no longer directly coupled to requiring an httpContext to send a response, unit testing controllers becomes extraordinarily simple as you no longer need to mock the entire response object, you can simply run assertions on the returned value. This API also allows us to make future improvements in this area and add in functionality that exists in similar frameworks (.NET WebAPI) such as media formatters, content negotation, etc.

import{injectable,inject}from"inversify";import{controller,httpGet,BaseHttpController,HttpResponseMessage,StringContent}from"inversify-express-utils"; @controller("/")classExampleControllerextendsBaseHttpController{ @httpGet("/")publicasyncget(){constresponse=newHttpResponseMessage(200);response.content=newStringContent("foo");returnresponse;}

On the BaseHttpController, we provide a litany of helper methods to ease returning common IHttpActionResults including

  • OkResult
  • OkNegotiatedContentResult
  • RedirectResult
  • ResponseMessageResult
  • StatusCodeResult
  • BadRequestErrorMessageResult
  • BadRequestResult
  • ConflictResult
  • CreatedNegotiatedContentResult
  • ExceptionResult
  • InternalServerError
  • NotFoundResult
  • JsonResult
  • StreamResult
import{injectable,inject}from"inversify";import{controller,httpGet,BaseHttpController}from"inversify-express-utils"; @controller("/")classExampleControllerextendsBaseHttpController{ @httpGet("/")publicasyncget(){returnthis.ok("foo");}

JsonResult

In some scenarios, you'll want to set the status code of the response. This can be done by using the json helper method provided by BaseHttpController.

import{controller,httpGet,BaseHttpController}from"inversify-express-utils"; @controller("/")exportclassExampleControllerextendsBaseHttpController{ @httpGet("/")publicasyncget(){constcontent={foo: "bar"};conststatusCode=403;returnthis.json(content,statusCode);}}

This gives you the flexability to create your own responses while keeping unit testing simple.

import{expect}from"chai";import{ExampleController}from"./example-controller";import{results}from"inversify-express-utils";describe("ExampleController",()=>{letcontroller: ExampleController;beforeEach(()=>{controller=newExampleController();});describe("#get",()=>{it("should have a status code of 403",async()=>{constresponse=awaitcontroller.get();expect(response).to.be.an.instanceof(results.JsonResult);expect(response.statusCode).to.equal(403);});});});

This example uses Mocha and Chai as a unit testing framework

StreamResult

In some cases, you'll want to proxy data stream from remote resource in response. This can be done by using the stream helper method provided by BaseHttpController. Useful in cases when you need to return large data.

import{inject}from"inversify";import{controller,httpGet,BaseHttpController}from"inversify-express-utils";importTYPESfrom"../constants";import{FileServiceInterface}from"../interfaces"; @controller("/cats")exportclassCatControllerextendsBaseHttpController{ @inject(TYPES.FileService)privatefileService: FileServiceInterface; @httpGet("/image")publicasyncgetCatImage(){constreadableStream=this.fileService.getFileStream("cat.jpeg");returnthis.stream(content,"image/jpeg",200);}}

HttpContext

The HttpContext property allow us to access the current request, response and user with ease. HttpContext is available as a property in controllers derived from BaseHttpController.

import{injectable,inject}from"inversify";import{controller,httpGet,BaseHttpController}from"inversify-express-utils"; @controller("/")classUserPreferencesControllerextendsBaseHttpController{ @inject("AuthService")privatereadonly_authService: AuthService; @httpGet("/")publicasyncget(){consttoken=this.httpContext.request.headers["x-auth-token"];returnawaitthis._authService.getUserPreferences(token);}}

If you are creating a custom controller you will need to inject HttpContext manually using the @injectHttpContext decorator:

import{injectable,inject}from"inversify";import{controller,httpGet,BaseHttpController,httpContext,interfaces}from"inversify-express-utils";constauthService=inject("AuthService") @controller("/")classUserPreferencesController{ @injectHttpContextprivatereadonly_httpContext: interfaces.HttpContext; @authServiceprivatereadonly_authService: AuthService; @httpGet("/")publicasyncget(){consttoken=this.httpContext.request.headers["x-auth-token"];returnawaitthis._authService.getUserPreferences(token);}}

AuthProvider

The HttpContext will not have access to the current user if you don't create a custom AuthProvider implementation:

constserver=newInversifyExpressServer(container,null,null,null,CustomAuthProvider);

We need to implement the AuthProvider interface.

The AuthProvider allow us to get a user (Principal):

import{injectable,inject}from"inversify";import{interfaces}from"inversify-express-utils";constauthService=inject("AuthService"); @injectable()classCustomAuthProviderimplementsinterfaces.AuthProvider{ @authServiceprivatereadonly_authService: AuthService;publicasyncgetUser(req: express.Request,res: express.Response,next: express.NextFunction): Promise<interfaces.Principal>{consttoken=req.headers["x-auth-token"]constuser=awaitthis._authService.getUser(token);constprincipal=newPrincipal(user);returnprincipal;}}

We also need to implement the Principal interface. The Principal interface allow us to:

  • Access the details of a user
  • Check if it has access to certain resource
  • Check if it is authenticated
  • Check if it is in a user role
classPrincipalimplementsinterfaces.Principal<T=unknown>{publicdetails: T;publicconstructor(details: T){this.details=details;}publicisAuthenticated(): Promise<boolean>{returnPromise.resolve(true);}publicisResourceOwner(resourceId: unknown): Promise<boolean>{returnPromise.resolve(resourceId===1111);}publicisInRole(role: string): Promise<boolean>{returnPromise.resolve(role==="admin");}}

We can then access the current user (Principal) via the HttpContext:

@controller("/")classUserDetailsControllerextendsBaseHttpController{ @inject("AuthService")privatereadonly_authService: AuthService; @httpGet("/")publicasyncgetUserDetails(){if(this.httpContext.user.isAuthenticated()){returnthis._authService.getUserDetails(this.httpContext.user.details.id);}else{thrownewError();}}}

BaseMiddleware

Extending BaseMiddleware allow us to inject dependencies and to access the current HttpContext in Express middleware function.

import{BaseMiddleware}from"inversify-express-utils"; @injectable()classLoggerMiddlewareextendsBaseMiddleware{ @inject(TYPES.Logger)privatereadonly_logger: Logger;publichandler(req: express.Request,res: express.Response,next: express.NextFunction){if(this.httpContext.user.isAuthenticated()){this._logger.info(`${this.httpContext.user.details.email} => ${req.url}`);}else{this._logger.info(`Anonymous => ${req.url}`);}next();}}

We also need to declare some type bindings:

constcontainer=newContainer();container.bind<Logger>(TYPES.Logger).to(Logger);container.bind<LoggerMiddleware>(TYPES.LoggerMiddleware).to(LoggerMiddleware);

We can then inject TYPES.LoggerMiddleware into one of our controllers.

@controller("/")classUserDetailsControllerextendsBaseHttpController{ @inject("AuthService")privatereadonly_authService: AuthService; @httpGet("/",TYPES.LoggerMiddleware)publicasyncgetUserDetails(){if(this.httpContext.user.isAuthenticated()){returnthis._authService.getUserDetails(this.httpContext.user.details.id);}else{thrownewError();}}}

Request-scope services

Middleware extending BaseMiddleware is capable of re-binding services in the scope of a HTTP request. This is useful if you need access to a HTTP request or context-specific property in a service that doesn't have the direct access to them otherwise.

Consider the below TracingMiddleware. In this example we want to capture the X-Trace-Id header from the incoming request and make it available to our IoC services as TYPES.TraceIdValue:

import{inject,injectable}from"inversify";import{BaseHttpController,BaseMiddleware,controller,httpGet}from"inversify-express-utils";import*asexpressfrom"express";constTYPES={TraceId: Symbol.for("TraceIdValue"),TracingMiddleware: Symbol.for("TracingMiddleware"),Service: Symbol.for("Service"),}; @injectable()classTracingMiddlewareextendsBaseMiddleware{publichandler(req: express.Request,res: express.Response,next: express.NextFunction){this.bind<string>(TYPES.TraceIdValue).toConstantValue(`${req.header('X-Trace-Id')}`);next();}} @controller("/")classTracingTestControllerextendsBaseHttpController{constructor(@inject(TYPES.Service)privatereadonlyservice: Service){super();} @httpGet("/",TYPES.TracingMiddleware)publicgetTest(){returnthis.service.doSomethingThatRequiresTheTraceID();}} @injectable()classService{constructor(@inject(TYPES.TraceIdValue)privatereadonlytraceID: string){}publicdoSomethingThatRequiresTheTraceID(){// ...}}

The BaseMiddleware.bind() method will bind the TYPES.TraceIdValue if it hasn't been bound yet or re-bind if it has already been bound.

Middleware decorators

You can use the @withMiddleware() decorator to register middleware on controllers and handlers. For example:

functionauthenticate(){returnwithMiddleware((req,res,next)=>{if(req.user===undefined){res.status(401).json({errors: ['You must be logged in to access this resource.']})}next()})}functionauthorizeRole(role: string){returnwithMiddleware((req,res,next)=>{if(!req.user.roles.includes(role)){res.status(403).json({errors: ['Get out.']})}next()})} @controller('/api/user') @authenticate()classUserController{ @httpGet('/admin/:id') @authorizeRole('ADMIN')publicgetById(@requestParam('id')id: string){ ... }}

You can also decorate controllers and handlers with middleware using BaseMiddleware identitifers:

classAuthenticationMiddlewareextendsBaseMiddleware{handler(req,res,next){if(req.user===undefined){res.status(401).json({errors: ['User is not logged in.']})}}}container.bind<BaseMiddleware>("AuthMiddleware").to(AuthenticationMiddleware) @controller('/api/users') @withMiddleware("AuthMiddleware")classUserController{ ... }

Route Map

If we have some controllers like for example:

@controller("/api/user")classUserControllerextendsBaseHttpController{ @httpGet("/")publicget(){return{};} @httpPost("/")publicpost(){return{};} @httpDelete("/:id")publicdelete(@requestParam("id")id: string){return{};}} @controller("/api/order")classOrderControllerextendsBaseHttpController{ @httpGet("/")publicget(){return{};} @httpPost("/")publicpost(){return{};} @httpDelete("/:id")publicdelete(@requestParam("id")id: string){return{};}}

We can use the prettyjson function to see all the available enpoints:

import{getRouteInfo}from"inversify-express-utils";import*asprettyjsonfrom"prettyjson";// ...letserver=newInversifyExpressServer(container);letapp=server.build();constrouteInfo=getRouteInfo(container);console.log(prettyjson.render({routes: routeInfo}));// ...

⚠️ Please ensure that you invoke getRouteInfo after invoking server.build()!

The output formatter by prettyjson looks as follows:

routes: - controller: OrderController endpoints: - route: GET /api/order/ - route: POST /api/order/ - path: DELETE /api/order/:id route: - @requestParam id - controller: UserController endpoints: - route: GET /api/user/ - route: POST /api/user/ - route: DELETE /api/user/:id args: - @requestParam id

Examples

Some examples can be found at the inversify-express-example repository.

License

License under the MIT License (MIT)

Copyright © 2016-2017 Cody Simms

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.

IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.