inversify-koa-utils
inversify-koa-utils is a module based on inversify-express-utils. This module has utilities for koa 2 applications development using decorators and IoC Dependency Injection (with inversify)
Installation
You can install inversify-koa-utils
using npm:
$ npm install inversify inversify-koa-utils reflect-metadata --save
The inversify-koa-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 koa 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 InversifyKoaServer constructor. This will allow it to register all controllers and their dependencies from your container and attach them to the koa app. Then just call server.build() to prepare your app.
In order for the InversifyKoaServer 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-koa-utils is empty and solely for convenience, so feel free to implement your own if you want.
; ;; // set up container; // note that you *must* bind your controllers to Controllercontainer.bindTYPE.Controller.toFooController.whenTargetNamed'FooController';container.bind'FooService'.toFooService; // create server;server.setConfig; ;app.listen3000;
InversifyKoaServer
A wrapper for an koa Application.
.setConfig(configFn)
Optional - exposes the koa application object for convenient loading of server-level middleware.
;// ...; server.setConfig;
.setErrorConfig(errorConfigFn)
Optional - like .setConfig()
, except this function is applied after registering all app middleware and controller routes.
;server.setErrorConfig;
.build()
Attaches all registered controllers and middleware to the koa 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 InversifyKoaServer
:
; ; ; ;
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
InversifyKoaServer
; ;
Using a custom koa application
It is possible to pass a custom koa.Application
instance to InversifyKoaServer
:
; ;//Do stuff with 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 koa routing method.
@SHORTCUT(path, [middleware, ...])
Shortcut decorators which are simply wrappers for @httpMethod
. Right now these include @httpGet
, @httpPost
, @httpPut
, @httpPatch
, @httpHead
, @httpDelete
, 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(name?: string)
Binds a method parameter to request.body or to a specific body property if a name is passed. If the bodyParser middleware is not used on the koa app, this will bind the method parameter to the koa request object.
@requestHeaders(name?: string)
Binds a method parameter to the request headers.
@cookies()
Binds a method parameter to the request cookies.
@context()
Binds a method parameter to the koa context object.
@next()
Binds a method parameter to the next() function.
@authorize([role: string, ...])
Ensures that only authenticated and authorized users can invoke this controller method. If authentication fails the status code 401 will be returned. If authorization fails the status code 403 will be returned. Even if authentication or authorization fail all middlewares (for router, controller and method) will be invoked. If you don't provide any roles only authentication will be ensured.
@authorizeAll([role: string, ...])
Ensures that only authenticated and authorized users can invoke the entire controller. Behaviour is the same as in @authorize
.
AuthProvider
You can provide a custom AuthProvider
to create and provida a principal for the current request.
;
We need to implement the AuthProvider
interface.
The AuthProvider
allow us to get an user (Principal
):
;;; ;
We also need to implement the Principal interface.
The 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 principal via the context state:
If you want to ensure that only authenticatied users can invoke a method you can use @authorize
:
BaseMiddleware
Extending BaseMiddleware
allow us to inject dependencies
in Koa middleware function.
;
We also need to declare some type bindings:
; container.bindTYPES.Logger .toLogger; container.bindTYPES.LoggerMiddleware .toLoggerMiddleware;
We can then inject TYPES.LoggerMiddleware
into one of our controllers.
container.bindTYPE.Controller .toMyController .whenTargetNamed"MyController";
License
License under the MIT License (MIT)
Copyright © 2017 Diego Plascencia
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.