koa-formatter

A response body formatter for Koa

Usage no npm install needed!

<script type="module">
  import koaFormatter from 'https://cdn.skypack.dev/koa-formatter';
</script>

README

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