Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/kaelzhang/ostai-koa-response
Response middleware for koa that will handle response body and errors
https://github.com/kaelzhang/ostai-koa-response
koa middleware
Last synced: about 2 months ago
JSON representation
Response middleware for koa that will handle response body and errors
- Host: GitHub
- URL: https://github.com/kaelzhang/ostai-koa-response
- Owner: kaelzhang
- License: other
- Created: 2020-05-05T08:17:15.000Z (almost 5 years ago)
- Default Branch: master
- Last Pushed: 2020-05-07T14:18:07.000Z (almost 5 years ago)
- Last Synced: 2024-12-13T13:16:21.570Z (about 2 months ago)
- Topics: koa, middleware
- Language: JavaScript
- Size: 4.88 KB
- Stars: 0
- Watchers: 3
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- Changelog: HISTORY.md
- License: LICENSE
Awesome Lists containing this project
README
[![Build Status](https://travis-ci.org/kaelzhang/ostai-koa-response.svg?branch=master)](https://travis-ci.org/kaelzhang/ostai-koa-response)
[![Coverage](https://codecov.io/gh/kaelzhang/ostai-koa-response/branch/master/graph/badge.svg)](https://codecov.io/gh/kaelzhang/ostai-koa-response)# @ostai/koa-response
Response middleware for koa that will handle response body and errors.
This module is designed to standardize server response structure.
## Install
```sh
$ npm i @ostai/koa-response
```## Usage
```js
const Koa = require('koa')
const Router = require('@koa/router')const response = require('@ostai/koa-response')
const app = new Koa()
const router = new Router()router.get('/foo', () => 'ok')
router.get('/bar', () => {
const error = new Error('bar')
error.status = 401
throw error
})app
.use(
response({
debug: true
})
)
.use(router.routes())
.use(router.allowedMethods())app.listen(8888)
``````sh
> curl http://localhost:8888/foo# http 200
# ok
``````sh
> curl http://localhost:8888/bar# http 401
# {"message":"bar"}
```## response(options?): Function
- **options?** `Object`
- **error?** `Function(ctx, error, rest): void` the method to handle error
- **success?** `Function(ctx, body, rest): void` the method to handle success
- **...rest?** `Object`
- **debug** `boolean=false` Which is used by the default value of `options.error`. By default, if `debug` is `false`, error response will not contain `message`.Returns `Function` the middleware function.
## License
[MIT](LICENSE)