Some utilities for the development of koa applications with Inversify
npm install inversify-koa-utilsinversify-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
$3
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'.
ts
import * as Koa from 'koa';
import { interfaces, Controller, Get, Post, Delete } from 'inversify-koa-utils';
import { injectable, inject } from 'inversify';
@controller('/foo')
@injectable()
export class FooController implements interfaces.Controller {
constructor( @inject('FooService') private fooService: FooService ) {}
@httpGet('/')
private index(ctx: Router.IRouterContext , next: () => Promise): string {
return this.fooService.get(ctx.query.id);
}
@httpGet('/basickoacascading')
private koacascadingA(ctx: Router.IRouterContext, nextFunc: () => Promise): string {
const start = new Date();
await nextFunc();
const ms = new Date().valueOf() - start.valueOf();
ctx.set("X-Response-Time", ${ms}ms);
}
@httpGet('/basickoacascading')
private koacascadingB(ctx: Router.IRouterContext , next: () => Promise): string {
ctx.body = "Hello World";
}
@httpGet('/')
private list(@queryParams('start') start: number, @queryParams('count') cound: number): string {
return this.fooService.get(start, count);
}
@httpPost('/')
private async create(@response() res: Koa.Response) {
try {
await this.fooService.create(req.body)
res.body = 201
} catch (err) {
res.status = 400
res.body = { error: err.message }
}
}
@httpDelete('/:id')
private delete(@requestParam("id") id: string, @response() res: Koa.Response): Promise {
return this.fooService.delete(id)
.then(() => res.body = 204)
.catch((err) => {
res.status = 400
res.body = { error: err.message }
})
}
}
`
$3
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.
`ts
import * as bodyParser from 'koa-bodyparser';
import { Container } from 'inversify';
import { interfaces, InversifyKoaServer, TYPE } from 'inversify-koa-utils';
// set up container
let container = new Container();
// note that you must bind your controllers to Controller
container.bind(TYPE.Controller).to(FooController).whenTargetNamed('FooController');
container.bind('FooService').to(FooService);
// create server
let server = new InversifyKoaServer(container);
server.setConfig((app) => {
// add body parser
app.use(bodyParser());
});
let app = server.build();
app.listen(3000);
`
InversifyKoaServer
A wrapper for an koa Application.
$3
Optional - exposes the koa application object for convenient loading of server-level middleware.
`ts
import * as morgan from 'koa-morgan';
// ...
let server = new InversifyKoaServer(container);
server.setConfig((app) => {
var logger = morgan('combined')
app.use(logger);
});
`
$3
Optional - like .setConfig(), except this function is applied after registering all app middleware and controller routes.
`ts
let server = new InversifyKoaServer(container);
server.setErrorConfig((app) => {
app.use((ctx, next) => {
console.error(err.stack);
ctx.status = 500
ctx.body = 'Something broke!';
});
});
`
$3
Attaches all registered controllers and middleware to the koa application. Returns the application instance.
`ts
// ...
let server = new InversifyKoaServer(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 InversifyKoaServer:
`ts
import * as Router from 'koa-router';
let container = new Container();
let router = new Router({
prefix: '/api',
});
let server = new InversifyKoaServer(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
InversifyKoaServer
`ts
let container = new Container();
let server = new InversifyKoaServer(container, null, { rootPath: "/api/v1" });
`
Using a custom koa application
It is possible to pass a custom koa.Application instance to InversifyKoaServer:
`ts
let container = new Container();
let app = new Koa();
//Do stuff with app
let server = new InversifyKoaServer(container, null, null, app);
`
Decorators
$3
Registers the decorated class as a controller with a root path, and optionally registers any global middleware for this controller.
$3
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.
$3
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 :smile:).