salix/services/client/common/util.js

70 lines
1.6 KiB
JavaScript

module.exports = installMethod;
function installMethod(model, methodName, filterCb) {
model.remoteMethod(methodName, {
description: 'List items using a filter',
accessType: 'READ',
accepts: [
{
arg: 'filter',
type: 'object',
required: true,
description: 'Filter defining where',
http: function(ctx) {
return ctx.req.query;
}
}
],
returns: {
arg: 'data',
type: [model.modelName],
root: true
},
http: {
verb: 'get',
path: `/${methodName}`
}
});
model.filter = function(params, cb) {
let filter = removeEmpty(filterCb(params));
model.find(filter, function(err, instances) {
if(!err) {
cb(null, instances);
}
})
};
}
function removeEmpty(o) {
if(Array.isArray(o)) {
let array = [];
for(let item of o) {
let i = removeEmpty(item);
if(!isEmpty(item))
array.push(item);
};
if(array.length > 0)
return array;
}
else if (typeof o === 'object') {
let object = {};
for(let key in o) {
let i = removeEmpty(o[key]);
if(!isEmpty(i))
object[key] = i;
}
if(Object.keys(object).length > 0)
return object;
}
else if (!isEmpty(o))
return o;
return undefined;
}
function isEmpty(value) {
return value === undefined || value === "";
}