JResponse for Node
Middleware for Node/Express. Use this middleware to get a standard output for the API Request.
You can also use JResponse as a simple object to standardize the Express router response.
When working with a large data set it obviously makes sense to offer pagination options to the endpoint.
To avoid writing your own pagination output into every endpoint, JResponse provides you JPagination.
JPagination is inspired by the Fractal Pagination for PHP,
and it offers two solution for paginate the response: JPaginator and JCursor
Install
npm i jresponse-node
Usage
Set the middleware (app.use() or router.use())
The module will append the formatted response to the res object of ExpressJS.
ES6
// routes.js ES6 const router = router router
ES5
// routes.js ES5 var express = var router = expressvar MyController = var jresponse = router router
Use 'JRes' instead the 'res' object in Express
ES6
// MyController.js { const items = await MyModel return resJRes }
ES5
// MyController.js var MyModel = const list = { MyModel }
Output
the JRes object will return always the same output: success, count, data, and errors
- success: (_boolean) true or false. True if there is not errors.
- count (integer). The size of data array.
- data (array). The data expected from request. If there are errors, it will be empty.
- errors (array). The errors occurred in the request. If there are some errors, success will be false.
Methods
- res.JRes.sendSuccess(data). Short success output, it will call the sendResponse method with success as true
- res.JRes.sendErrors(message [, code]). Short error output, it will call the sendResponse method with success as false
- res.JRes.appendError(message [, code]). Append the current error message to the JRes object, and will set the currect error code.
- res.JRes.sendResponse(success, data, errors). You can use this method in place of the previous ones
- res.JRes.paginate(JPagination). Get the pagination object in the response (see the Pagination section)
Customize the output
- res.JRes.merge(data). Merge the data object passed to the function (object or array) with the default JResponse object
- res.JRes.key(key, value). Add the key and the value to the default JResponse object
resJRes // or resJResresJRes
Output
Use "JRes" and pass it to "res" Express object
You can use the JRes in order to format the response, without use the 'res' Express route object. In this call, you can call JResponse statically
// MyController.js { try const orders = await MyModel const result = JResponse return resstatus200 catche const result = JResponse return resstatus404 }
Static Methods
- JResponse.success(data). Short success output, it will call the sendResponse method with success as true
- JResponse.errors(errors). Short error output, it will call the sendResponse method with success as false
- JResponse.send(success, data, errors). You can use this method in place of the previous ones
Pagination
Pagination is the process of dividing content into result-set and JPagination provides you with two solutions.
JPaginator
JPaginator is an auto form of pagination. TO perform the response it requires the Request object, and a total items count. This adds a pagination node to the response, which will contain next/previous links if applicable. Use the method res.JRes.paginate(<JPagination>) to append the pagination to JResponse. This intelligence comes at the cost of having to count the number of entries in a database on each call.
For some data sets this might not be an issue, but for some it certainly will. If pure speed is an issue, consider using JCursors instead.
// MyController.js { const counter = await MyModel const totalItems = countercount // For example 10 items // Optionals parameters for the pagination const options = maxItems: 250 metaKey: 'pagination' limitKey: 'limit' pageKey: 'page' // Instantiate the pagination let paging = req totalItems options const items = await MyModel return resJRes}
For example, you can call the following address and see the output.
http://localhost:3000/test?limit=2&page=1
Output
Options
- maxItems. Set the max results per page. If the "limit" is greater than maxItems the limit will be equal to this value (default: 250)
- metaKey. Set the "pagination" key name for the JResponse object (default: "pagination")
- limitKey. Set the "limit" key name for the JPagination object. If you change this name you will change also the key in the querystring (default: "limit").
- pageKey. Set the "page" key name for the JPagination object. If you change this name you will change also the key in the querystring (default: "page").
JCursor
When we have large sets of data and running a MyModel.findAndCountAll() isn't really an option, we need a proper way of fetching results. One of the approaches is to use cursors that will indicate to your backend where to start fetching results. It's really easy to use.
// MyController.js { let Cursor = req Cursor let direction = Cursordirection let items = await MyModel if itemslength == 0 return resJRes if Cursordirection == 'after' items = items // Update maxId and sinceId values const beforeId = itemsitemslength - 1_id const afterId = items0_id return resJRes}
For example, you can call the following address and see the output.
http://localhost:3000/items?limit=2
If you move to the next url, the response will be the following
Methods
- displayFilter([id] [, dialect]). Display the filter node in pagination object response. You can use the returned value to set the query filter automatically. Set the id with the identifier key for your collection (default "id") Choose the proper dialect for your database between "nosql", "sql", "plain" (default "nosql").
Output for nosql
"filter": {
"_id": {
"$lt": "5c793543ac87ecc484832810"
}
}
Output for sql
"filter": {
"_id": "< 5c793543ac87ecc484832810"
}
Output for plain
"filter": {
"_id": "less than 5c793543ac87ecc484832810"
}
Options
The same of JPaginator