1.0.0 • Published 4 years ago

koa-handler v1.0.0

Weekly downloads
2
License
MIT
Repository
github
Last release
4 years ago

Koa Handler

Configure a koa server with a provided configuration

Build Status Coverage Status Maintainability Language grade: JavaScript tested with jest code style: prettier

Install

$ npm install koa-handler

Features

  • Reuse configuration across projects (router, middleware, etc) with custom presets
  • Automatically inject middlewares, context and routes to your server

Usage

const Koa = require('koa');
const serverLoader = require("koa-handler")(Koa);

// your own configuration
const { router1, router2 } = require("./modules/routers");
const db = require("./modules/db");
const preset1 = require("./modules/preset1");
const preset2 = require("./modules/preset2");

// configuration
const server_config = {
  routers: [router1, router2],
  ctx: { db }, // optional
  presets: [preset1, preset2] // optional
};

const server = serverLoader(server_config);

//  HTTP server listening
server.listen(config.SERVER_PORT, () => {
  console.info(`Server listening at ${config.SERVER_PORT}`);
});

Create a preset

  • A preset is nothing else than returning a object.
  • The returned object can have three type of fields :
    • routers: an array of koa routers
    • middlewares: an array of koa middlewares
    • ctx: A Koa context object
    • all these fields are optional

example :

const dummyPreset = () => ({
  ctx: { dummy: "dummy example" }
});

API

koaHandler(config) ⇒ Object

Configure a koa server with a provided configuration

Returns: Object - configured Koa server ready to by started

ParamTypeDefaultDescription
KoaObjectKoa builder
configObjectconfig object
config.routersObject[][]koa routers
config.middlewareObject[][]koa middlewares
config.ctxObject[][]Items that must be added into koa context
config.presetsObject[][]preconfigured set of middleware, routers and ctx

License

MIT © saxjst