Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix invalid range unit override #51

Merged
merged 1 commit into from
Jan 3, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ The middleware can be configured with the following parameters:

- `allowAll`: Whether to accept `*` as range-specifier.
- `maximum`: Maximum number of items allowed per page (`50` by default).
- `unit`: Range unit to be used when no `Range` header is provided (`items` by default).
- `unit`: Accepted range unit (`items` by default).

You can change the defaults by doing:

Expand Down
7 changes: 5 additions & 2 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -42,10 +42,13 @@ function middleware({ allowAll = true, maximum = 50, unit = 'items' } = {}) {
throw new MalformedRangeError();
}

// Update `limit`, `offset` and `unit` values.
if (range.unit !== unit) {
throw new MalformedRangeError();
}

// Update `limit`, `offset` values.
first = range.first;
last = range.last;
unit = range.unit;

if (!allowAll && last === '*') {
throw new RangeNotSatisfiableError();
Expand Down
22 changes: 9 additions & 13 deletions test/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,15 @@ describe('middleware', () => {
.expect(412, 'Precondition Failed');
});

it('should return 412 if the `Range` unit is not supported', () => {
app.use(middleware({ unit: 'bytes' }));

return request(server)
.get('/')
.set('Range', 'items=0-*')
.expect(412);
});

it('should return 416 if the `Range` is invalid', () => {
app.use(middleware());

Expand Down Expand Up @@ -279,19 +288,6 @@ describe('middleware', () => {
.set('Range', `items=${firstPosition}-5`);
});

it('should expose the given `range-unit`', () => {
app.use(middleware({ unit: 'bytes' }));

app.use(ctx => {
expect(ctx.pagination.unit).toEqual('foobar');
});

return request(server)
.get('/')
.set('Range', 'foobar=0-5')
.expect('Content-Range', 'foobar 0-5/*');
});

it('should set the `byte-range-spec` to `*` if length is 0', () => {
app.use(middleware({ unit: 'bytes' }));

Expand Down