Skip to content

WebForgeOSS/koa-handler

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

20 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

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

Param Type Default Description
Koa Object Koa builder
config Object config object
[config.routers] Object[] [] koa routers
[config.middleware] Object[] [] koa middlewares
[config.ctx] Object[] [] Items that must be added into koa context
[config.presets] Object[] [] preconfigured set of middleware, routers and ctx

License

MIT © saxjst

Releases

No releases published

Packages

No packages published