Skip to content

Commit

Permalink
Change how sorting query param order is specified
Browse files Browse the repository at this point in the history
  • Loading branch information
hagopj13 committed Nov 17, 2019
1 parent c7879be commit cd683e9
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 5 deletions.
9 changes: 7 additions & 2 deletions src/utils/service.util.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,15 @@
const getQueryOptions = query => {
const sort = query.sort || '+createdAt';
const page = query.page * 1 || 1;
const limit = query.limit * 1 || 100;
const skip = (page - 1) * limit;

return { sort, limit, skip };
const sort = {};
if (query.sortBy) {
const parts = query.sortBy.split(':');
sort[parts[0]] = parts[1] === 'desc' ? -1 : 1;
}

return { limit, skip, sort };
};

module.exports = {
Expand Down
2 changes: 1 addition & 1 deletion src/validations/user.validation.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ const getUsers = {
query: Joi.object().keys({
name: Joi.string(),
role: Joi.string(),
sort: Joi.string(),
sortBy: Joi.string(),
limit: Joi.number().integer(),
page: Joi.number().integer(),
}),
Expand Down
18 changes: 16 additions & 2 deletions tests/integration/user.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -205,13 +205,27 @@ describe('User routes', () => {
expect(res.body[1].id).toBe(userTwo._id.toHexString());
});

test('should correctly sort returned array if sort param is specified', async () => {
test('should correctly sort returned array if descending sort param is specified', async () => {
await insertUsers([userOne, userTwo, admin]);

const res = await request(app)
.get('/v1/users')
.set('Authorization', `Bearer ${adminAccessToken}`)
.query({ sort: 'role' })
.query({ sortBy: 'role:desc' })
.send()
.expect(httpStatus.OK);

expect(res.body).toHaveLength(3);
expect(res.body[0].id).toBe(userOne._id.toHexString());
});

test('should correctly sort returned array if ascending sort param is specified', async () => {
await insertUsers([userOne, userTwo, admin]);

const res = await request(app)
.get('/v1/users')
.set('Authorization', `Bearer ${adminAccessToken}`)
.query({ sortBy: 'role:asc' })
.send()
.expect(httpStatus.OK);

Expand Down

0 comments on commit cd683e9

Please sign in to comment.