Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/njakob/koa-formatter
A response body formatter for Koa
https://github.com/njakob/koa-formatter
Last synced: 17 days ago
JSON representation
A response body formatter for Koa
- Host: GitHub
- URL: https://github.com/njakob/koa-formatter
- Owner: njakob
- License: mit
- Created: 2016-07-19T13:37:45.000Z (over 8 years ago)
- Default Branch: master
- Last Pushed: 2018-04-20T14:23:51.000Z (over 6 years ago)
- Last Synced: 2024-12-16T18:29:34.859Z (17 days ago)
- Language: JavaScript
- Size: 6.84 KB
- Stars: 0
- Watchers: 2
- Forks: 1
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# koa-formatter
A response body formatter for [Koa](https://github.com/koajs/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](https://nodei.co/npm/koa-formatter.png?downloads=true)](https://nodei.co/npm/koa-formatter/)
```
$ npm install koa-formatter
```## Usage
```javascript
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.
```javascript
app.use(formatter({ formatter: formatter.defaultFormatter() }));
app.use(function(ctx) {
ctx.throw('simple error');
});
``````json
{
"ok": 0,
"status": 500,
"errors": [ "simple error" ]
}
``````javascript
app.use(formatter({ formatter: formatter.defaultFormatter() }));
app.use(function(ctx) {
ctx.result = [ 'John' ];
});
``````json
{
"ok": 1,
"status": 200,
"result": [
"John"
]
}
```## Licences
[MIT](LICENSE)