express-api-responder
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
Setup
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
Outputs 200
Return Success Response
Returns a JSON body. By default returns HTTP status code 200 but a code can be passed.
res;
Output 200
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;
Output 404
or
Paginated Responses
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;
Output: 200
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.
res;
In production environment 500
if not in a production environment 500
Signing Responses
Must provide a JWT secret or private key to the responder options.
app; res;
Response 200
No Content
res;
Extra 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.
app; res;
Response 409
Run Tests
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