1.0.1 • Published 9 years ago
koa2-module v1.0.1
koa2-module
Abstract class for Koa2 module building with async/await support.
Requirements
- Koa 2.x
- Node 7.x with
--harmonyflag
Installation
npm install koa2-module --saveBasic example
const Koa = require( 'koa' );
const Module = require( 'koa2-module' );
class FantasticModule extends Module {
moduleLoad( options ) {
this.body = 'Hello ' + options.body;
return this.fantasticMiddlware();
}
fantasticMiddlware() {
return async (ctx) => {
ctx.body = this.body;
};
}
}
const app = new Koa();
new FantasticModule( app, { body: 'Fantastic!' } );
app.listen( 3000 );Usage
constructor(app, options)
constructor takes two arguments, Koa2 application instance and options object. Should not be overridden.
Options
There are only two build in options, enabled and disabled, which can be used to disable the whole module.
| Option | Default value |
|---|---|
| enabled | true |
| disabled | false |
Example
new FantasticModule( app, {
enabled: process.env.NODE_ENV === 'production';
} );moduleLoad(options)
moduleLoad(options) is main lifecycle method executed during application initialization.
It takes options object passed from the constructor and should return a method that returns
Koa2 middleware function. It can be a common function or async function.
Common function example
moduleLoad( options ) {
this.something = doSomething( options );
return this.middleware();
}Async function example
async moduleLoad( options ) {
this.something = await doSomething( options );
return this.middleware();
}Middleware
Module can have any number of methods returning middleware functions. In moduleLoad() method
you can control which middleware will be used.
Example
class FantasticModule extends Module {
async moduleLoad( options ) {
var result = await doSomething( options );
if( process.env.NODE_ENV === 'production' ) {
return this.productionMiddleware();
}
else if( process.env.NODE_ENV === 'development' ) {
return this.developmentMiddleware();
}
else {
return this.otherMiddleware();
}
}
productionMiddleware() {
return async (ctx) => {
ctx.body = 'Production!';
};
}
developmentMiddleware() {
return async (ctx) => {
ctx.body = 'Development!';
};
}
otherMiddleware() {
return async (ctx) => {
ctx.body = 'Other?';
};
}
}