express-api-responder1.1.1 • Public • Published
A small Express.js Middleware for conveniently formatting JSON responses. This package builds into the Express.js response object and allows you to return data in the following:
- A response after a successful request
- Paginated data for a list
- An error for a bad request or other errors
- No content after a deletion
- Signing a request with a JWT auth token
- Catch a server error and return an error message without important knowledge of the system
npm install express-responder --save
Can be used by your whole app or a router
var repsonder = ;app;//orvar router = express;router;//How to userouter
Return Success Response
Returns a JSON body. By default returns HTTP status code 200 but a code can be passed.
Return Error Response
Returns a JSON body with a message field for error handling. Defaults the HTTP status code to 400. The message also defaults to a description based on the code
res;//Or default to the code descriptorres;
Returns a JSON object with a list of data as well as some useful fields. Defaults 200 HTTP status code
var data = name: 'Eric' name: 'Dufresne' ...;var totalCount = 50;var page = 1;var limit = 25;res;
Catch Internal Server Error
Returns an error message based on the HTTP status code given for an unexpected error. Defaults to HTTP status code 500 but a code can be passed.
In production environment
if not in a production environment
Must provide a JWT secret or private key to the responder options.
You can include the status code as well as a success flag in all the JSON responses by passing extra options to the middleware.
Tests use a mock server with the middleware in place. Can run using mocha as well as with istanbul
npm run test npm run cover