Feat add support of limit, offset, order
Allows passing these as query params to list and scope methods.
This commit is contained in:
44
src/utils.js
44
src/utils.js
@ -1,9 +1,13 @@
|
||||
import { omit, identity } from 'lodash';
|
||||
import { omit, identity, toNumber, isString, isUndefined } from 'lodash';
|
||||
import { notImplemented } from 'boom';
|
||||
|
||||
const sequelizeKeys = ['include', 'order', 'limit', 'offset'];
|
||||
|
||||
export const parseInclude = request => {
|
||||
const include = Array.isArray(request.query.include) ? request.query.include
|
||||
: [request.query.include];
|
||||
const include = Array.isArray(request.query.include)
|
||||
? request.query.include
|
||||
: [request.query.include]
|
||||
;
|
||||
|
||||
const noGetDb = typeof request.getDb !== 'function';
|
||||
const noRequestModels = !request.models;
|
||||
@ -27,7 +31,7 @@ export const parseInclude = request => {
|
||||
};
|
||||
|
||||
export const parseWhere = request => {
|
||||
const where = omit(request.query, 'include');
|
||||
const where = omit(request.query, sequelizeKeys);
|
||||
|
||||
for (const key of Object.keys(where)) {
|
||||
try {
|
||||
@ -40,6 +44,38 @@ export const parseWhere = request => {
|
||||
return where;
|
||||
};
|
||||
|
||||
export const parseLimitAndOffset = (request) => {
|
||||
const { limit, offset } = request.query;
|
||||
const out = {};
|
||||
if (!isUndefined(limit)) {
|
||||
out.limit = toNumber(limit);
|
||||
}
|
||||
if (!isUndefined(offset)) {
|
||||
out.offset = toNumber(offset);
|
||||
}
|
||||
return out;
|
||||
};
|
||||
|
||||
export const parseOrder = (request) => {
|
||||
const { order } = request.query;
|
||||
|
||||
if (!order) return null;
|
||||
|
||||
// transform to an array so sequelize will escape the input for us and
|
||||
// maintain security. See http://docs.sequelizejs.com/en/latest/docs/querying/#ordering
|
||||
if (isString(order)) return order.split(' ');
|
||||
|
||||
for (const key of Object.keys(order)) {
|
||||
try {
|
||||
order[key] = JSON.parse(order[key]);
|
||||
} catch (e) {
|
||||
//
|
||||
}
|
||||
}
|
||||
|
||||
return order;
|
||||
};
|
||||
|
||||
export const getMethod = (model, association, plural = true, method = 'get') => {
|
||||
const a = plural ? association.original.plural : association.original.singular;
|
||||
const b = plural ? association.original.singular : association.original.plural; // alternative
|
||||
|
Reference in New Issue
Block a user