koa-middleware-adapter
v5.2.5
Published
Functions and promises can be used as middleware in koa.
Downloads
330
Readme
Koa Middleware Adapter

Functions and promises can be used as middleware in koa.
const Koa = require('koa');
const adapter = require('koa-middleware-adapter');
const app = new Koa();
app.use(adapter.create(() => 'Hello, World!'));
const port = 4000;
app.listen(port, () => {
console.log(`server is listening to port ${port}`);
});
Document
Install
$ npm i koa-middleware-adapter
Usage
const Koa = require('koa');
const Router = require('koa-router');
const bodyParser = require('koa-bodyparser');
const adapter = require('koa-middleware-adapter');
const UserDao = require('./userDao');
const userDao = new UserDao();
async function findUserInfo(userId, userDao) {
const user = await userDao.findById(Number(userId));
if (!user) throw new adapter.NotFound('User Not Found');
return user;
}
async function createUserInfo(user, userDao) {
await userDao.insert(user);
return user;
}
const findUserMiddleware = adapter.create(findUserInfo, {
status: 200,
parameters: [
new adapter.parameter.Parameter(adapter.parameter.where.params, { name: 'id', index: 0 }),
new adapter.parameter.Parameter(userDao, { index: 1 }),
],
});
const findUserInContextMiddleware = adapter.create(findUserInfo, {
status: 200,
parameters: [
new adapter.parameter.Parameter(new adapter.parameter.where.Where('user', true), { name: 'id', index: 0 }),
new adapter.parameter.Parameter(userDao, { index: 1 }),
],
});
const createUserMiddleware = adapter.create(createUserInfo, {
status: null,
parameters: [
new adapter.parameter.Parameter(adapter.parameter.where.body, { index: 0 }),
new adapter.parameter.Parameter(userDao, { index: 1 }),
],
response: new adapter.response.Response(adapter.response.where.context, { name: 'user' }),
});
const router = new Router();
router.get('/users/:id', findUserMiddleware);
router.post('/user', createUserMiddleware, findUserInContextMiddleware);
const app = new Koa();
app.use(bodyParser());
app.use(router.routes());
app.use(router.allowedMethods());
const port = 4000;
app.listen(port, () => {
console.log(`server is listening to port ${port}`);
});Request
POST http://localhost:4000/user
{ "username": "test", "password": "test" }
Response
status: 200
{ "username": "test", "password": "test", "id": 0 }
Request
- GET http://localhost:4000/users/0
Response
status: 200
{ "username": "test", "password": "test", "id": 0 }
Spec
Adapt
adapter.create(listener, { status, type, parameters, response, handlers, thisArg });
Parameters
function Parameter(
where = new Where(null, true, true, true),
options = {},
) {
this.where = where;
this.name = options.name || null;
this.as = options.as || null;
this.index = options.index || 0;
this.combineLevel = options.combineLevel || 0;
}Parameters defines the information of the parameters to pass.
wheredefines where to find the parameter.- If
whereis not an instance ofWhere, the parameter iswhere. - If
whereis an instance ofWhere, the parameter is found inctxwith information fromwhere.
- If
nameis the name of the parameter.- If
nameexists, the same name is taken from the parameter's location.
- If
combineLevelis the level at which the imported arguments are to be combined.0means the imported parameter is the parameter to pass.1means the imported parameter is a child of the parameter to pass.
asspecifies a name when passing a parameter.indexis index of the parameter to pass.
The default value is
params,query,header,body,cookiesdefined.
Response
function Response(
where = new Where(null, true, true, true),
options = {},
) {
this.where = where;
this.name = options.name || null;
this.type = options.type;
}- The response determines how to handle the lister's response
wheredefines where to bind the response.- If
whereis not an instance ofWhere, the response is injected inwhere. - If
whereis an instance ofWhere, the position is found inctxwith information fromwhereand inject the response.
- If
nameis the name of the response.- If
nameexists, the same name is defined in the position to inject the response.
- If
- The default value is
body, which binds the request value to the body of the response.
Where
function Where(name, context, koa, node, setterAndGetter) {
this.name = name;
this.context = context;
this.koa = koa;
this.node = node;
this.setterAndGetter = setterAndGetter;
}- Where defines where to find the parameter.
nameis the name of the location from which to retrieve the parameter.contextmeans to find the location of a parameter inctx.koameans to find the location of a parameter inctx.request.nodemeans to find the location of a parameter inctx.req.
setterAndGettermeans to usesetorgetmethod to extract or inject object, ifsetorgetmethod is exist.
Handlers
const handlers = { extractParameterHandler, injectResponseHandler, errorHandler };Extract Parameter Handler
function extractParameterHandler(ctx, parameters) {}Inject Response Handler
function injectResponseHandler(ctx, result, options = { response, status, type }) {}Error Handler
function errorHandler(ctx, error) {}
thisArg
- If this is exist, listener call by thisArg.
- If this type is function, listener call by result of thisArg.
