2016-07-06 01:33:03 +00:00
|
|
|
import { omit, identity } from 'lodash';
|
2016-03-10 07:18:30 +00:00
|
|
|
|
|
|
|
export const parseInclude = request => {
|
|
|
|
const include = Array.isArray(request.query.include) ? request.query.include
|
|
|
|
: [request.query.include];
|
|
|
|
|
2016-07-06 01:33:03 +00:00
|
|
|
const noGetDb = typeof request.getDb !== 'function';
|
|
|
|
const noRequestModels = !request.models;
|
|
|
|
|
|
|
|
if (noGetDb && noRequestModels) {
|
|
|
|
return new Error('`request.getDb` or `request.models` are not defined. Be sure to load hapi-sequelize before hapi-sequelize-crud.');
|
|
|
|
}
|
|
|
|
|
|
|
|
const {models} = noGetDb ? request : request.getDb();
|
|
|
|
|
2016-03-10 07:18:30 +00:00
|
|
|
return include.map(a => {
|
2016-07-06 01:33:03 +00:00
|
|
|
if (typeof a === 'string') return models[a];
|
2016-03-10 07:18:30 +00:00
|
|
|
|
|
|
|
if (a && typeof a.model === 'string' && a.model.length) {
|
2016-07-06 01:33:03 +00:00
|
|
|
a.model = models[a.model];
|
2016-03-10 07:18:30 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return a;
|
2016-07-06 01:33:03 +00:00
|
|
|
}).filter(identity);
|
2016-06-30 13:58:02 +00:00
|
|
|
};
|
2016-03-10 07:18:30 +00:00
|
|
|
|
|
|
|
export const parseWhere = request => {
|
|
|
|
const where = omit(request.query, 'include');
|
|
|
|
|
|
|
|
for (const key of Object.keys(where)) {
|
|
|
|
try {
|
|
|
|
where[key] = JSON.parse(where[key]);
|
|
|
|
} catch (e) {
|
|
|
|
//
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return where;
|
2016-06-30 13:58:02 +00:00
|
|
|
};
|
2016-03-10 07:18:30 +00:00
|
|
|
|
|
|
|
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
|
|
|
|
const fn = model[`${method}${a}`] || model[`${method}${b}`];
|
|
|
|
if (fn) return fn.bind(model);
|
|
|
|
|
|
|
|
return false;
|
2016-06-30 13:58:02 +00:00
|
|
|
};
|