Simple and structured application level JSON responses for your API. Based on JSend specification (http://labs.omniti.com/labs/jsend).
npm install --save koa-jsend
In your koa app.
var Koa = require('koa')
, jsend = require('koa-jsend')
;
var app = new Koa();
app.use(jsend());
Instead of using ctx.body=
to send JSON responses, use one of the functions in ctx
.
- data: Optional response data.
app.use(async function (ctx, next){
ctx.success({
name: 'Samora',
sex: 'Male',
nationality: 'Ghanaian'
});
});
// JSON response
// {
// "status": "success",
// "data": {
// "name": "Samora",
// "sex": "Male",
// "nationality": "Ghanaian"
// }
// }
- errors: Required error(s) data.
app.use(async function (ctx, next){
ctx.fail({
name: 'Name is required.'
});
});
// JSON response
// {
// "status": "fail",
// "data": {
// "name": "Name is required."
// }
// }
- message: Required error message or
Error
object. - data: Optional error data.
- code: Optional error code.
app.use(async function (ctx, next){
ctx.error('Something went wrong.', null, 8);
});
// JSON response
// {
// "status": "error",
// "message": "Something went wrong.",
// "code": 8
// }
Sends a ctx.success
response if no err
is passed.
Sends a ctx.error
response if err
is passed.
- err: Error object or message string or null.
- data: Optional
- code: Optional
app.use(async function (ctx, next){
ctx.jsend(null, {
name: 'Samora',
sex: 'Male',
nationality: 'Ghanaian'
});
});
// JSON response
// {
// "status": "success",
// "data": {
// "name": "Samora",
// "sex": "Male",
// "nationality": "Ghanaian"
// }
// }
app.use(async function (ctx, next){
ctx.jsend(Error('Something went wrong.'));
});
// JSON response
// {
// "status": "error",
// "message": "Something went wrong.",
// }
MIT