salix/services/client/common/util.js

70 lines
1.6 KiB
JavaScript
Raw Normal View History

2017-02-21 10:36:43 +00:00
module.exports = installMethod;
2017-02-21 15:21:55 +00:00
function installMethod(model, methodName, filterCb) {
model.remoteMethod(methodName, {
2017-02-21 10:36:43 +00:00
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',
2017-02-21 15:21:55 +00:00
type: [model.modelName],
2017-02-21 10:36:43 +00:00
root: true
},
http: {
2017-02-21 15:21:55 +00:00
verb: 'get',
path: `/${methodName}`
2017-02-21 10:36:43 +00:00
}
});
2017-02-21 15:21:55 +00:00
model.filter = function(params, cb) {
2017-02-21 10:36:43 +00:00
let filter = removeEmpty(filterCb(params));
2017-02-21 15:21:55 +00:00
model.find(filter, function(err, instances) {
2017-02-21 10:36:43 +00:00
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 === "";
}