jsend
Utilities and middleware to assist with sending and handling jsend responses.
Installation
npm install -S jsend
Response Creation
Responses can be created using the success
, fail
, and error
methods:
// You can pass data or a jsend response to successjsend; // { status: 'success', data: { foo: 'bar' } }jsend; // { status: 'success', data: [ 'foo', 'bar' ] }jsend; // { status: 'success', data: 1337 }jsend; // { status: 'success', data: false } // You can pass data or a jsend response to failjsend; // { status: 'fail', data: { itsa: 'trap' } }jsend; // { status: 'fail', data: true } // You can pass a message or an object with a message and optionally data and codejsend; // { status: 'error', message: 'No soup for you!' }jsend; // { status: 'error', code: 123, message: 'No soup for you!' }jsend; // { status: 'error', code: 123, message: 'No soup for you!', data: false }
Node-style Callbacks
The fromArguments
method can be used to create jsend responses from node-style (i.e. (err, data)
) callback arguments:
;
Http Middleware
The jsend middleware has methods for easily sending "succeess", "fail" and "error" responses:
expressApp; expressApp;
Or you can use res.jsend
as a callback to respond automatically with a jsend wrapped response:
expressApp; expressApp;
same as:
expressApp; expressApp;
Responding with jsend sans-middleware
If you don't want to use the middleware you can simply create jsend responses and send them with res.json
:
;
Response Validation
By default jsend.isValid
validates that all required properties exist.
var jsend = ; // Returns truejsend; // Returns falsejsend; // Returns truejsend;
Using the strict
flag causes jsend.isValid
to also validate that extraneous properties do not exist.
var jsend = strict:true ; // Returns truejsend; // Returns falsejsend; // Returns falsejsend;
Response Forwarding
You can forward a jsend response to a node style callback using the forward
method.
jsend;