Some utilities for the development of express applications with Inversify.
You can install
inversify-express-utils using npm:
npm install inversify inversify-express-utils reflect-metadata --save
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.
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'.
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.
Controller interface exported by inversify-express-utils is empty and solely for convenience, so feel free to implement your own if you want.
;;;// declare metadata by @controller annotation;// set up container;// set up bindingscontainer.bind'FooService'.toFooService;// create server;server.setConfig;;app.listen3000;
Important information about the @controller decorator
email@example.com 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
⚠️ 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.
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.
A wrapper for an express Application.
Optional - exposes the express application object for convenient loading of server-level middleware.
Optional - like
.setConfig(), except this function is applied after registering all app middleware and controller routes.
Attaches all registered controllers and middleware to the express application. Returns the application instance.
// ...;server.setConfigconfigFn.setErrorConfigerrorConfigFn.build.listen3000, 'localhost', callback;
Using a custom Router
It is possible to pass a custom
Router instance to
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
Using a custom express application
It is possible to pass a custom
express.Application instance to
;;//Do stuff with app;
@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
@All. For anything more obscure, use
@httpMethod (Or make a PR 😄).
Binds a method parameter to the request object.
Binds a method parameter to the response object.
Binds a method parameter to request.params object or to a specific parameter if a name is passed.
Binds a method parameter to request.query or to a specific query parameter if a name is passed.
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.
Binds a method parameter to the request headers.
Binds a method parameter to the request cookies.
Binds a method parameter to the next() function.
Binds a method parameter to the user principal obtained from the AuthProvider.
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 are 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.
On the BaseHttpController, we provide a litany of helper methods to ease returning common IHttpActionResults including
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
This gives you the flexability to create your own responses while keeping unit testing simple.
HttpContext property allow us to access the current request,
response and user with ease.
HttpContext is available as a property
in controllers derived from
If you are creating a custom controller you will need to inject
HttpContext will not have access to the current user if you don't
create a custom
We need to implement the
AuthProvider allow us to get an user (
We also need to implement the Principal interface.
Principal interface allow us to:
- Access the details of an user
- Check if it has access to certain resource
- Check if it is authenticated
- Check if it is in an user role
We can then access the current user (Principal) via the
BaseMiddleware allow us to inject dependencies
and to be access the current
HttpContext in Express middleware function.
We also need to declare some type bindings:
We can then inject
TYPES.LoggerMiddleware into one of our controllers.
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
BaseMiddleware.bind() method will bind the
TYPES.TraceIdValue if it hasn't been bound yet or re-bind if it has
already been bound.
If we have some controllers like for example:
We can use the
prettyjson function to see all the available enpoints:
;;// ...;;;console.logprettyjson.render;// ...
⚠️ Please ensure that you invoke
The output formatter by
prettyjson looks as follows:
routes:-controller: OrderControllerendpoints:-route: GET /api/order/-route: POST /api/order/-path: DELETE /api/order/:idroute:- @requestParam id-controller: UserControllerendpoints:-route: GET /api/user/-route: POST /api/user/-route: DELETE /api/user/:idargs:- @requestParam id
Some examples can be found at the inversify-express-example repository.
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.