koa-formatter

0.1.0 • Public • Published

koa-formatter

A response body formatter for Koa.

This middleware can be used to format the JSON result of API calls.

Features

  • Custom format function
  • Handle aggregation of errors
  • Flowtype definition

Installation

NPM

$ npm install koa-formatter

Usage

const Koa = require('koa');
const formatter = require('koa-formatter');
 
const app = new Koa();
 
app.use(formatter());
app.use(formatter({ formatter: function(ctx, errors) {
  ctx.body = (errors.length ? 'some errors occurred' : 'ok');
}}))

Formatter

The library comes with a built-in formatter.

app.use(formatter({ formatter: formatter.defaultFormatter() }));
app.use(function(ctx) {
  ctx.throw('simple error');
});
{
  "ok": 0,
  "status": 500,
  "errors": [ "simple error" ]
}
app.use(formatter({ formatter: formatter.defaultFormatter() }));
app.use(function(ctx) {
  ctx.result = [ 'John' ];
});
{
  "ok": 1,
  "status": 200,
  "result": [
    "John"
  ]
}

Licences

MIT

Package Sidebar

Install

npm i koa-formatter

Weekly Downloads

1

Version

0.1.0

License

MIT

Last publish

Collaborators

  • njakob