express-sequelize-autocrud
Version:
Express Sequelize AutoCRUD: Simplify API development with automatic CRUD routes for Sequelize models in Express.js.
48 lines • 1.97 kB
JavaScript
import { isIncludeExcludeMatchCriteria } from './config.js';
import { crudError } from '../utils.js';
import { GET_LIST_DEFAULT_FILTERABLE_FIELDS, GET_LIST_DEFAULT_SORTABLE_FIELDS, } from '../config.js';
export const buildOptionsFromQueryParams = (q, options) => {
const { _sort, _order, _start, _end, ...where } = q;
const { limit, order } = options;
const queryLimit = _end
? parseInt(_end) - (parseInt(_start) || 0)
: undefined;
return {
where,
limit: queryLimit && (!limit || limit >= queryLimit) ? queryLimit : limit,
offset: parseInt(_start) || 0,
order: _sort ? [[_sort, _order || 'DESC']] : order,
};
};
export const checkFilterableFields = (filterableFields = GET_LIST_DEFAULT_FILTERABLE_FIELDS) => {
return async (req, res, next) => {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { _sort, _order, _start, _end, ...where } = req.query;
if (where &&
!(await isIncludeExcludeMatchCriteria(filterableFields, Object.keys(where), req, res)).result) {
res
.status(400)
.json(crudError(`Can't filter by fields [${Object.keys(where).join(', ')}]`));
}
else {
next();
}
};
};
export const checkSortableFields = (sortableFields = GET_LIST_DEFAULT_SORTABLE_FIELDS) => {
return async (req, res, next) => {
const { _sort } = req.query;
if (_sort &&
!(await isIncludeExcludeMatchCriteria(sortableFields, _sort.toString(), req, res)).result) {
res.status(400).json(crudError(`Can't sort by field [${_sort}]`));
}
else {
next();
}
};
};
export const setContentRange = (res, key, offset, length, total) => {
const range = length === 0 ? '0-0/0' : `${offset}-${offset + length}/${total}`;
res.setHeader('Content-Range', `${key} ${range}`);
};
//# sourceMappingURL=query.js.map