Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/nswbmw/koa-res
Format koa's respond json.
https://github.com/nswbmw/koa-res
Last synced: 21 days ago
JSON representation
Format koa's respond json.
- Host: GitHub
- URL: https://github.com/nswbmw/koa-res
- Owner: nswbmw
- Created: 2016-04-18T04:30:47.000Z (over 8 years ago)
- Default Branch: master
- Last Pushed: 2022-12-15T03:34:07.000Z (almost 2 years ago)
- Last Synced: 2024-09-30T21:05:07.939Z (about 1 month ago)
- Language: JavaScript
- Size: 10.7 KB
- Stars: 15
- Watchers: 3
- Forks: 1
- Open Issues: 0
-
Metadata Files:
- Readme: readme.md
Awesome Lists containing this project
README
## koa-res
Format koa's respond json.
### Install
```sh
$ npm i koa-res --save
```### Examples
**Error Response**
```js
const app = new require('koa')
const koaRes = require('koa-res')app.use(koaRes({ debug: true }))
app.use(() => {
hi()
})app.listen(3000)
```Output:
```js
GET / -> 500{
code: 500,
message: 'hi is not defined',
stack: 'ReferenceError: hi is not defined\n at Object. (...)'
}
```**Normal Response**
```js
const app = new require('koa')
const koaRes = require('koa-res')app.use(koaRes())
app.use((ctx) => {
ctx.body = {
username: 'username',
gender: 'male'
}
})app.listen(3000)
```Output:
```js
GET / -> 200{
code: 200,
data: { username: 'username', gender: 'male' }
}
```### Custom fields
```js
const app = new require('koa')
const koaRes = require('koa-res')app.use(koaRes({
custom: (ctx) => {
return {
name: 'my-api'
}
}
}))app.use((ctx) => {
ctx.body = 'This is my api'
})app.listen(3000)
```Output:
```js
GET / -> 200{
name: 'my-api',
code: 200,
data: 'This is my api'
}
```### ctx.\_returnRaw
You must put ctx.\_returnRaw on top of route controller.
```js
const app = new require('koa')
const koaRes = require('koa-res')app.use(koaRes())
app.use((ctx) => {
ctx._returnRaw = true
ctx.body = {
username: 'username',
gender: 'male'
}
})app.listen(3000)
```Output:
```js
GET / -> 200{
username: 'username',
gender: 'male'
}
```### Test
```sh
$ npm test
```### License
MIT