Skip to content

Commit

Permalink
feat: ✨ add content-range header on getList routes
Browse files Browse the repository at this point in the history
  • Loading branch information
doralteres committed Sep 8, 2023
1 parent 4fda39e commit 6805c8f
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 4 deletions.
6 changes: 5 additions & 1 deletion example/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,11 @@ initDB().then(sequelize => {
users: {
model: users,
operations: {
getList: {filterableFields: ['id', 'gender'], limit: 100},
getList: {
pagination: true,
filterableFields: ['id', 'gender'],
limit: 100,
},
getOne: {attributes: ['id', 'fullName']},
create: {
creatableFields: {exclude: ['id']},
Expand Down
12 changes: 12 additions & 0 deletions src/middleware/query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,3 +70,15 @@ export const checkSortableFields = (sortableFields: customFields = []) => {
}
};
};

export const setContentRange = (
res: Response,
key: string,
offset: number,
length: number,
total: number
) => {
const range =
length === 0 ? '0-0/0' : `${offset}-${offset + length}/${total}`;
res.setHeader('Content-Range', `${key} ${range}`);
};
12 changes: 9 additions & 3 deletions src/routes/getList.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ import {
buildOptionsFromQueryParams,
checkFilterableFields,
checkSortableFields,
setContentRange,
} from '../middleware/query';
import {SequelizeScopeError} from 'sequelize';
import {getSequelizeErrorMessage} from '../utils';

const getListRoute = (
Expand Down Expand Up @@ -49,8 +49,14 @@ const getListRoute = (
...queryOptions,
where: {...options.where, ...queryOptions.where},
});
// TODO: set PAGINATION
res.json({rows, count});
setContentRange(
res,
model.name,
queryOptions.offset || 0,
rows.length,
count
);
res.json(rows);
} else {
const data = await model.findAll({
...options,
Expand Down

0 comments on commit 6805c8f

Please sign in to comment.