Skip to content

Commit

Permalink
Merge pull request #3 from darthwesker/next
Browse files Browse the repository at this point in the history
1.1.0
  • Loading branch information
darthwesker authored Feb 20, 2019
2 parents 70df620 + 5592bb7 commit 32e6b66
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 14 deletions.
10 changes: 10 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,16 @@ Default value: `[ "*.find" ]`, which auto added to find method of all models.

### `relatedModels`: Boolean

Apply `Content-Range` to all related models.

### `defaultLimit`: Integer

Set the default value when no limit parameter is passed on filter.

### `maxLimit`: Integer

Set the maximum value of the limit paramater on filter.

## Tips

To get all records, use: `{ "limit": 0 }`
Expand Down
41 changes: 28 additions & 13 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,10 @@ module.exports = function(app, options) {

const applyRange = function(model, name, ctx, next) {
if (!ctx.res._headerSent) {
let filter;
let limit = 50;
const maxLimit = options && options.maxLimit;
let limit = options && options.defaultLimit || 50;
let offset = 0;
let filter;

if (!ctx.args)
ctx.args = {};
Expand All @@ -17,25 +18,39 @@ module.exports = function(app, options) {
if (ctx.args.filter.where)
filter = ctx.args.filter.where;

if (ctx.args.filter.limit)
limit = ctx.args.filter.limit;
else
if (
ctx.args.filter.limit == null ||
ctx.args.filter.limit !== parseInt(ctx.args.filter.limit, 10)
) {
ctx.args.filter.limit = limit;
} else if (maxLimit &&
maxLimit > 0 &&
(ctx.args.filter.limit > maxLimit || ctx.args.filter.limit == 0)
) {
limit = maxLimit;
ctx.args.filter.limit = maxLimit;
} else {
limit = ctx.args.filter.limit;
}

if (ctx.args.filter.offset)
offset = ctx.args.filter.offset;
else
ctx.args.filter.offset = offset;

model.count(filter, function(err, count) {
const last = Math.min(offset + limit, count);
ctx.res.set('Access-Control-Expose-Headers', 'Content-Range');
ctx.res.set(
'Content-Range',
`${name.toLowerCase()} ${offset}-${last}/${count}`
);
if (typeof model.count === 'function') {
model.count(filter, function(err, count) {
const last = Math.min(offset + limit, count);
ctx.res.set('Access-Control-Expose-Headers', 'Content-Range');
ctx.res.set(
'Content-Range',
`${name.toLowerCase()} ${offset}-${last}/${count}`
);
next();
});
} else {
next();
});
}
}
};

Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "loopback-content-range",
"version": "1.0.2",
"version": "1.1.0",
"description": "Add Content header to all search requests for Loopback 3",
"main": "index.js",
"scripts": {
Expand Down

0 comments on commit 32e6b66

Please sign in to comment.