jsender
v0.0.6
Published
Simple and structured application level JSON responses for Express. Based on JSend specification.
Downloads
12
Maintainers
Readme
JSender
Simple and structured application level JSON responses for Express. Based on JSend specification (http://labs.omniti.com/labs/jsend).
Installation
npm install jsender
Setup the middleware in your Express app. Before any routes.
var express = require('express')
, jsender = require('jsender')
;
var app = express();
// ... (other middlewares)
app.use(jsender());
app.get('/', function (req, res){
res.success({
notice: 'Hello, World!'
});
});
// JSON Response
// {
// "status": "success",
// "data": {
// "notice": "Hello, World!"
// }
// }
API
JSender augments the node res
object with the following methods.
success(data)
- data: Optional response data object.
function (req, res){
res.success({
notice: 'Hello, World!'
});
};
// JSON Response
// {
// "status": "success",
// "data": {
// "notice": "Hello, World!"
// }
// }
fail(data)
- data: Required failure data.
function (req, res){
res.fail({
name: 'Name is required.'
});
};
// JSON Response
// {
// "status": "fail",
// "data": {
// "name": "Name is required."
// }
// }
error(message, data, code)
- message: Required error message.
- data: Optional error data.
- code: Optional error code.
function (req, res){
res.error('Server error.');
};
// JSON Response
// {
// "status": "error",
// "message": "Server error."
// }
jsend(err, data)
- err: An error object or
null
. - data: Optional response data object.
function (req, res){
books.find()
.exec(res.jsend);
};
// same as
function (req, res){
books.find()
.exec(function (err, data){
if (err)
return res.jsend(err);
res.jsend(null, data);
});
};