wizni-koa-server
v0.0.1
Published
Koa server initialization
Downloads
4
Readme
Koa Server
Creates a Koa server with various middleware installed. Currently, this is intended for pure-API servers.
Example
const createApp = require('wizni-koa-server');
const app = createApp({
// som eoptions
});
// set some route definitions
app.route('/').get(async ctx => {
ctx.body = 'some body';
});
// create the server
// NOTE: you cannot add routes after you create the server
const server = app.createServer();
server.listen(3000, err => {
if (err) throw err;
});
Notes
- Adds a lot of Koa middleware so that they are builtin.
- Koa prefers functions over middleware, i.e.
fn(ctx)
vs.app.use(fn)
. - Koa v2 is used, not v1. Koa v2 uses
async functions
instead of generators and will be stable as soon asasync functions
are in v8.
API
This module returns a function that returns a koa
app instance.
const createServer = require('wizni-koa-server');
app
See https://github.com/koajs/koa/blob/v2.x/docs/api/index.md
const app = createServer(options);
const app = createServer({
})
const server = app.createServer();
Create an HTTP server instance. Only do this when all the routes are defined.
app.route(path)[method](fn)
Registers an async
koa function at the specified path
and method
.
Paths will be executed in the order in which they are defined.
ctx
See:
- https://github.com/koajs/koa/blob/v2.x/docs/api/context.md
- https://github.com/koajs/koa/blob/v2.x/docs/api/request.md
- https://github.com/koajs/koa/blob/v2.x/docs/api/response.md
In Koa v2.x, the ctx
is used instead of v1.x's this
.
const { name, pass } = ctx.basicAuth
Basic auth, courtesy of https://github.com/koajs/ctx-basic-auth.
ctx.cacheControl()
Easy cache control management, courtsey of https://github.com/koajs/ctx-cache-control.
const body = await ctx.request.json([limit])
JSON request body parsing, courtsey of https://github.com/koajs/body-parsers.
const body = await ctx.request.urlencoded([limit])
Urlencoded form body parsing, courtsey of https://github.com/koajs/body-parsers.
const text = await ctx.request.text([limit])
Text request body parsing, courtsey of https://github.com/koajs/body-parsers.
const buffer = await ctx.request.buffer([limit])
Buffer request body parsing, courtsey of https://github.com/koajs/body-parsers.