/koa-jsend

Simple and structured application level JSON responses for Koa based on JSend specification.

Primary LanguageJavaScript

KOA JSend

Simple and structured application level JSON responses for your API. Based on JSend specification (http://labs.omniti.com/labs/jsend).

Installation

npm install --save koa-jsend

In your koa app.

var Koa = require('koa')
  , jsend = require('koa-jsend')
  ;

var app = new Koa();

app.use(jsend());

API

Instead of using ctx.body= to send JSON responses, use one of the functions in ctx.

ctx.success(data)

  • 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"
//   }
// }

ctx.fail(errors)

  • 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."
//   }
// }

ctx.error(message, data, code)

  • 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
// }

ctx.jsend(err, data, code)

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.",
// }

License

MIT