Skip to content

Commit

Permalink
Add RangeValidator for take paramater
Browse files Browse the repository at this point in the history
  • Loading branch information
bnematzadeh committed Nov 10, 2024
1 parent 216f637 commit 071e253
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 0 deletions.
5 changes: 5 additions & 0 deletions server/lib/user/user.get.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
const { Op } = require('sequelize');
const Sequelize = require('sequelize');
const { RangeError } = require('../../utils/coreErrors');
const db = require('../../models');

const DEFAULT_OPTIONS = {
fields: ['id', 'firstname', 'lastname', 'selector', 'email'],
expand: [],
skip: 0,
limit: 20,
order_dir: 'ASC',
order_by: 'firstname',
};
Expand Down Expand Up @@ -40,6 +42,9 @@ async function get(options) {
};

if (optionsWithDefault.take) {
if (optionsWithDefault.take > DEFAULT_OPTIONS.limit) {
throw new RangeError('The value of the limit parameter is out of range');
}
queryParams.limit = optionsWithDefault.take;
}

Expand Down
14 changes: 14 additions & 0 deletions server/test/controllers/user/user.get.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -70,4 +70,18 @@ describe('GET /api/v1/user', () => {
.expect('Content-Type', /json/)
.expect(401);
});

it('should return 500 for an out-of-range limit value', async () => {
await authenticatedRequest
.get('/api/v1/user?take=30')
.expect('Content-Type', /json/)
.expect(500);
});

it('should return 200 for a limit value within the valid range.', async () => {
await authenticatedRequest
.get('/api/v1/user?take=15')
.expect('Content-Type', /json/)
.expect(200);
});
});
8 changes: 8 additions & 0 deletions server/utils/coreErrors.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,13 @@ class NotFoundError extends Error {
}
}

class RangeError extends Error {
constructor(message) {
super();
this.message = message;
}
}

class NoValuesFoundError extends Error {
constructor(message) {
super();
Expand Down Expand Up @@ -80,4 +87,5 @@ module.exports = {
ConflictError,
ForbiddenError,
TooManyRequests,
RangeError,
};

0 comments on commit 071e253

Please sign in to comment.