Sort JSON file with NODEJS - arrays

I just started using NodeJS (as of yesterday) I have managed to retrieve JSON data from an API as seen in the code below:
var request = require('request');
var fs = require('fs');
const pug = require('pug');
request.get('APICALL', function(err, data) {
if (err) { }
else {
console.log(data);
fs.writeFile('industries.txt', JSON.stringify(data));
}
});
The JSON data that my request.get returns can be found here JSON FILE
What I want to do is sort through this data, find out which revenue and industry ID appears the most (i.e for this data it's "revenue:8" and "industry:69") once this is done I want to return only companies who match both revenue 8 and industry 9.
Is this possible and what would be the best way to approach such a task?

You can count the revenue - industry_id occurences, sort descending and then filter by that:
let arr = [{"id":1,"domain":"google.com","alexa_rank":1,"country":236,"employees":"7","revenue":"8","industry_id":"69"},{"id":3,"domain":"youtube.com","alexa_rank":2,"country":236,"employees":"5","revenue":"8","industry_id":"69"},{"id":2,"domain":"facebook.com","alexa_rank":3,"country":236,"employees":"6","revenue":"8","industry_id":"69"},{"id":4,"domain":"yahoo.com","alexa_rank":6,"country":236,"employees":"6","revenue":"8","industry_id":"69"},{"id":111,"domain":"reddit.com","alexa_rank":9,"country":236,"employees":"3","revenue":"2","industry_id":"69"},{"id":9,"domain":"twitter.com","alexa_rank":12,"country":236,"employees":"5","revenue":"8","industry_id":"69"},{"id":230,"domain":"360.cn","alexa_rank":20,"country":46,"employees":"5","revenue":"8","industry_id":"69"},{"id":30,"domain":"weibo.com","alexa_rank":22,"country":46,"employees":"5","revenue":"2","industry_id":"69"},{"id":19,"domain":"google.de","alexa_rank":23,"country":236,"employees":"7","revenue":"8","industry_id":"65"},{"id":23,"domain":"google.co.uk","alexa_rank":24,"country":236,"employees":"7","revenue":"8","industry_id":"45"},{"id":12,"domain":"linkedin.com","alexa_rank":25,"country":236,"employees":"5","revenue":"8","industry_id":"69"},{"id":25,"domain":"google.fr","alexa_rank":26,"country":76,"employees":"1","revenue":"2","industry_id":"65"},{"id":46,"domain":"google.ru","alexa_rank":27,"country":236,"employees":"0","revenue":"8","industry_id":"69"},{"id":33,"domain":"google.com.br","alexa_rank":28,"country":32,"employees":"3","revenue":"3","industry_id":"47"},{"id":22,"domain":"yandex.ru","alexa_rank":29,"country":182,"employees":"5","revenue":"7","industry_id":"69"},{"id":20,"domain":"google.com.hk","alexa_rank":31,"country":46,"employees":"0","revenue":"8","industry_id":"69"},{"id":101,"domain":"netflix.com","alexa_rank":32,"country":236,"employees":"5","revenue":"8","industry_id":"38"},{"id":35,"domain":"google.it","alexa_rank":34,"country":236,"employees":"6","revenue":"8","industry_id":"113"},{"id":3351716,"domain":"ntd.tv","alexa_rank":36,"country":236,"employees":"4","revenue":"0","industry_id":"13"},{"id":77,"domain":"imgur.com","alexa_rank":37,"country":236,"employees":"3","revenue":"2","industry_id":"69"},{"id":21,"domain":"ebay.com","alexa_rank":38,"country":236,"employees":"6","revenue":"8","industry_id":"69"},{"id":41,"domain":"google.es","alexa_rank":39,"country":236,"employees":"1","revenue":"2","industry_id":"65"},{"id":74,"domain":"pornhub.com","alexa_rank":40,"country":58,"employees":"1","revenue":"3","industry_id":"38"},{"id":13,"domain":"msn.com","alexa_rank":41,"country":236,"employees":"8","revenue":"8","industry_id":"69"},{"id":18,"domain":"wordpress.com","alexa_rank":43,"country":236,"employees":"4","revenue":"3","industry_id":"69"},{"id":507,"domain":"aliexpress.com","alexa_rank":44,"country":46,"employees":"7","revenue":"8","industry_id":"69"},{"id":42,"domain":"livejasmin.com","alexa_rank":47,"country":128,"employees":"1","revenue":"0","industry_id":"38"},{"id":28,"domain":"microsoft.com","alexa_rank":48,"country":236,"employees":"8","revenue":"8","industry_id":"25"},{"id":58,"domain":"google.ca","alexa_rank":49,"country":236,"employees":"7","revenue":"8","industry_id":"69"},{"id":44,"domain":"tumblr.com","alexa_rank":50,"country":236,"employees":"4","revenue":"5","industry_id":"69"},{"id":107,"domain":"stackoverflow.com","alexa_rank":52,"country":236,"employees":"4","revenue":"3","industry_id":"69"},{"id":2553,"domain":"twitch.tv","alexa_rank":53,"country":236,"employees":"4","revenue":"4","industry_id":"69"},{"id":40,"domain":"imdb.com","alexa_rank":58,"country":236,"employees":"4","revenue":"3","industry_id":"69"},{"id":488,"domain":"github.com","alexa_rank":61,"country":236,"employees":"4","revenue":"5","industry_id":"25"},{"id":239,"domain":"pinterest.com","alexa_rank":62,"country":236,"employees":"4","revenue":"4","industry_id":"69"},{"id":1853,"domain":"popads.net","alexa_rank":65,"country":53,"employees":"1","revenue":"1","industry_id":"84"},{"id":51,"domain":"xvideos.com","alexa_rank":66,"country":59,"employees":"0","revenue":"0","industry_id":"38"},{"id":7154677,"domain":"diply.com","alexa_rank":68,"country":40,"employees":"3","revenue":"0","industry_id":"100"},{"id":245,"domain":"csdn.net","alexa_rank":69,"country":46,"employees":"3","revenue":"2","industry_id":"69"},{"id":189,"domain":"wikia.com","alexa_rank":72,"country":236,"employees":"4","revenue":"3","industry_id":"69"},{"id":275,"domain":"google.com.tw","alexa_rank":74,"country":218,"employees":"0","revenue":"8","industry_id":"95"},{"id":8456,"domain":"whatsapp.com","alexa_rank":75,"country":236,"employees":"3","revenue":"2","industry_id":"69"},{"id":56,"domain":"xhamster.com","alexa_rank":78,"country":58,"employees":"1","revenue":"0","industry_id":"38"},{"id":44705842,"domain":"txxx.com","alexa_rank":81,"country":0,"employees":"1","revenue":"0","industry_id":"38"},{"id":2793171,"domain":"coccoc.com","alexa_rank":84,"country":243,"employees":"3","revenue":"0","industry_id":"65"},{"id":1000482,"domain":"bongacams.com","alexa_rank":85,"country":58,"employees":"0","revenue":"0","industry_id":"38"},{"id":92,"domain":"google.pl","alexa_rank":86,"country":236,"employees":"6","revenue":"8","industry_id":"77"},{"id":794,"domain":"pixnet.net","alexa_rank":86,"country":218,"employees":"3","revenue":"0","industry_id":"69"},{"id":249,"domain":"dropbox.com","alexa_rank":87,"country":236,"employees":"5","revenue":"7","industry_id":"69"},{"id":62718286,"domain":"porn555.com","alexa_rank":90,"country":0,"employees":"0","revenue":"0","industry_id":"38"},{"id":141,"domain":"google.co.th","alexa_rank":91,"country":236,"employees":"6","revenue":"8","industry_id":"69"},{"id":1215,"domain":"gmw.cn","alexa_rank":92,"country":46,"employees":"0","revenue":"0","industry_id":"97"},{"id":130,"domain":"google.com.pk","alexa_rank":93,"country":236,"employees":"3","revenue":"2","industry_id":"84"},{"id":317,"domain":"china.com","alexa_rank":98,"country":46,"employees":"5","revenue":"8","industry_id":"100"},{"id":148727,"domain":"amazon.in","alexa_rank":100,"country":236,"employees":"8","revenue":"8","industry_id":"69"},{"id":115,"domain":"google.com.ar","alexa_rank":101,"country":11,"employees":"0","revenue":"8","industry_id":"69"},{"id":375,"domain":"soundcloud.com","alexa_rank":103,"country":83,"employees":"4","revenue":"3","industry_id":"69"},{"id":39,"domain":"fc2.com","alexa_rank":104,"country":236,"employees":"0","revenue":"0","industry_id":"69"},{"id":62729524,"domain":"clicksgear.com","alexa_rank":104,"country":0,"employees":"0","revenue":"0","industry_id":"84"},{"id":2711,"domain":"bbc.com","alexa_rank":107,"country":235,"employees":"6","revenue":"8","industry_id":"13"},{"id":109,"domain":"google.nl","alexa_rank":108,"country":155,"employees":"7","revenue":"8","industry_id":"65"},{"id":146,"domain":"adf.ly","alexa_rank":110,"country":235,"employees":"1","revenue":"2","industry_id":"65"},{"id":7739,"domain":"uptodown.com","alexa_rank":111,"country":209,"employees":"1","revenue":"2","industry_id":"69"},{"id":26665,"domain":"ettoday.net","alexa_rank":111,"country":46,"employees":"0","revenue":"0","industry_id":"100"},{"id":240,"domain":"booking.com","alexa_rank":112,"country":155,"employees":"6","revenue":"8","industry_id":"69"},{"id":95,"domain":"dailymotion.com","alexa_rank":113,"country":76,"employees":"4","revenue":"5","industry_id":"69"},{"id":1022,"domain":"quora.com","alexa_rank":115,"country":236,"employees":"3","revenue":"2","industry_id":"69"},{"id":48,"domain":"ask.com","alexa_rank":116,"country":236,"employees":"4","revenue":"5","industry_id":"69"},{"id":2353727,"domain":"espn.com","alexa_rank":117,"country":236,"employees":"5","revenue":"7","industry_id":"13"},{"id":7170357,"domain":"blastingnews.com","alexa_rank":119,"country":216,"employees":"4","revenue":"2","industry_id":"100"},{"id":86,"domain":"nytimes.com","alexa_rank":120,"country":236,"employees":"5","revenue":"8","industry_id":"97"},{"id":1000001,"domain":"blogger.com","alexa_rank":124,"country":236,"employees":"7","revenue":"8","industry_id":"69"},{"id":106,"domain":"vimeo.com","alexa_rank":125,"country":236,"employees":"4","revenue":"5","industry_id":"69"},{"id":10725,"domain":"savefrom.net","alexa_rank":125,"country":182,"employees":"1","revenue":"0","industry_id":"69"},{"id":28040741,"domain":"daikynguyenvn.com","alexa_rank":126,"country":236,"employees":"0","revenue":"0","industry_id":"100"},{"id":547,"domain":"detik.com","alexa_rank":127,"country":103,"employees":"4","revenue":"5","industry_id":"100"},{"id":1282,"domain":"stackexchange.com","alexa_rank":129,"country":236,"employees":"4","revenue":"3","industry_id":"69"},{"id":200,"domain":"google.co.ve","alexa_rank":131,"country":236,"employees":"0","revenue":"8","industry_id":"69"},{"id":157,"domain":"google.co.za","alexa_rank":132,"country":205,"employees":"2","revenue":"2","industry_id":"82"},{"id":221,"domain":"salesforce.com","alexa_rank":132,"country":236,"employees":"6","revenue":"8","industry_id":"69"},{"id":2394,"domain":"vice.com","alexa_rank":135,"country":236,"employees":"5","revenue":"8","industry_id":"118"},{"id":4637,"domain":"tribunnews.com","alexa_rank":136,"country":103,"employees":"3","revenue":"2","industry_id":"87"},{"id":88,"domain":"ebay.co.uk","alexa_rank":138,"country":236,"employees":"6","revenue":"8","industry_id":"69"},{"id":177,"domain":"slideshare.net","alexa_rank":140,"country":236,"employees":"5","revenue":"8","industry_id":"69"},{"id":1816926,"domain":"theguardian.com","alexa_rank":141,"country":235,"employees":"5","revenue":"6","industry_id":"97"},{"id":1594,"domain":"spotify.com","alexa_rank":143,"country":215,"employees":"5","revenue":"8","industry_id":"95"},{"id":113,"domain":"xnxx.com","alexa_rank":144,"country":59,"employees":"1","revenue":"0","industry_id":"38"},{"id":236,"domain":"google.com.vn","alexa_rank":145,"country":243,"employees":"0","revenue":"8","industry_id":"9"},{"id":44263656,"domain":"adexchangeprediction.com","alexa_rank":146,"country":0,"employees":"0","revenue":"0","industry_id":"84"},{"id":884,"domain":"buzzfeed.com","alexa_rank":147,"country":236,"employees":"5","revenue":"5","industry_id":"69"},{"id":4263,"domain":"chaturbate.com","alexa_rank":148,"country":236,"employees":"2","revenue":"1","industry_id":"38"},{"id":161,"domain":"nicovideo.jp","alexa_rank":149,"country":111,"employees":"4","revenue":"5","industry_id":"69"},{"id":225,"domain":"google.gr","alexa_rank":149,"country":86,"employees":"1","revenue":"1","industry_id":"35"},{"id":158,"domain":"chase.com","alexa_rank":151,"country":236,"employees":"8","revenue":"8","industry_id":"44"},{"id":148,"domain":"mozilla.org","alexa_rank":153,"country":236,"employees":"5","revenue":"6","industry_id":"69"},{"id":723,"domain":"avito.ru","alexa_rank":153,"country":182,"employees":"4","revenue":"4","industry_id":"69"},{"id":87,"domain":"cnet.com","alexa_rank":155,"country":236,"employees":"4","revenue":"5","industry_id":"100"},{"id":224,"domain":"google.com.co","alexa_rank":156,"country":49,"employees":"7","revenue":"2","industry_id":"47"},{"id":340,"domain":"indeed.com","alexa_rank":157,"country":236,"employees":"5","revenue":"8","industry_id":"69"},{"id":558,"domain":"flipkart.com","alexa_rank":157,"country":102,"employees":"6","revenue":"8","industry_id":"69"}]
let mostOccurence = [...arr.reduce((a,b) => {
a.set(b.revenue + ":" + b.industry_id, a.has(b.revenue + ":" + b.industry_id) ? a.get(b.revenue + ":" + b.industry_id) + 1 : 1);
return a;
}, new Map)].sort((a,b) => b[1] - a[1])[0][0];
let split = mostOccurence.split(':'), revToLook = split[0], indToLook = split[1];
let filtered = arr.filter(e => e.revenue === revToLook && e.industry_id === indToLook);
console.log(filtered);

Related

Firebase's onValue only get data once and does not update when placed inside a loop in React's useEffect

My goal is to get multiple data based on a list of data the customer requested so I put the codes inside useEffect. If the array contains the list of things the customer wants, then it grab those data from the server so the user can manipulate it. So far, it works fine but when the database updates, onValue is not triggered to grab the new data to update the render.
Here is my code. Thank you for helping me in advance.
// Getting data
useEffect(() => {
if (empDataArr.length > 1) {
let fromDay = parseInt(dateHandler(startDate).dateStamp);
let toDay = parseInt(dateHandler(endDate).dateStamp);
let tempLogArr = [];
empDataArr.forEach((emp) => {
let qLogEvent = query(child(shopRef(shopId), emp.id + "/log_events"), orderByChild("dateStamp"), startAt(fromDay), endAt(toDay));
// This is the part I need help
onValue(qLogEvent, (snap) => {
let logEventArr = [];
let val = snap.val();
if (val === null) {
} else {
Object.keys(val).forEach((key) => {
let id = key;
let dateStamp = val[key].dateStamp;
let direction = val[key].direction;
let time = val[key].timeStamp + "";
let timeStamp = time.substring(8, 10) + ":" + time.substring(10, 12);
logEventArr.push({ direction: direction, timeStamp: timeStamp, dateStamp: dateStamp, id: id });
});
tempLogArr.push({
id: emp.id,
logEvent: logEventArr,
});
}
});
});
setLogDataArr(tempLogArr.map((x) => x));
}
}, [empDataArr, shopId, startDate, endDate]);
useEffect(() => {
console.log(logDataArr);
}, [logDataArr]);
I have tried using return onValue() and const logData = onValue() but they do not work (and I do not expect the former one to work either).

AWS GraphQL JSON string formatting

I'm attempting to create an object value to pass into DynamoDB using AWS AppSync and GraphQL. I'm very close to what I need but I'm stumbling on nested JSON.
Let's say I have an array:
let officers = [{"id":"0","IgRole":"Role1","IgName":"testname1","IgEmail":"testemail1","IgPhone":"testphone1","IgStart":"teststart1","IgEnd":"testend1"},
{"id":"1","IgRole":"Role2","IgName":"testname2","IgEmail":"testemail2","IgPhone":"testphone2","IgStart":"teststart2","IgEnd":"testend2"}]
I now want to create an object with each of the array values as a child object so, I do this:
for (let i in officers) {
officersJson['"' + officers[i].IgRole + '"'] = '{"Name":"' + officers[i].IgName + '","Email":"' + officers[i].IgEmail + '","Phone":"' + officers[i].IgPhone + '","Date commenced":"' + officers[i].IgStart + '","Date to end":"' + officers[i].IgEnd + '"}';
}
Here are the results:
Object {
"Role1": "{'Name':'testname1','Email':'testemail1','Phone':'testphone1','Date commenced':'teststart1','Date to end':'testend1'}",
"Role2": "{'Name':'testname2','Email':'testemail2','Phone':'testphone2','Date commenced':'teststart2','Date to end':'testend2'}"
}
I think the problem is that the each entire key / value is not in string format. If you look at
"Role1": "{......
you can see that the string breaks.
and this is the response from AWS:
Variable 'Officers' has an invalid value. Unable to parse {\"Role1\"={\"Nam
See the = sign
How can I format the object into a complete JSON string? I was fairly pleased I managed to get anywhere near the format I needed but this last bit has me stumped.
Finally worked it out. I needed a slightly different approach. Posting it in case it helps anyone else:
Firstly I created an array of roles, as this will be the keys for the value objects:
for (let i in officers) {
roles.push(officers[i].IgRole);
}
I then created a new array.
let arrOfficers = [];
for (let i in officers) {
arrOfficers.push(officers[i]);
}
I then use a function to create objects from an array:
function groupBy(objectArray, property) {
return objectArray.reduce(function (acc, obj) {
let key = obj[property];
if (!acc[key]) {
acc[key] = [];
}
acc[key].push(obj);
return acc;
}, {});
}
let newresult = groupBy(arrOfficers, "IgRole");
Finally I create my object and then stringify it:
let officersJson = {};
for (let i in roles) {
officersJson[roles[i]] = newresult[roles[i]][0];
}
theObjectIwant = JSON.stringify(officersJson)

How to extract information from nested arrays with multiple objects?? (AdminReport.Activities.list)

Could anyone point me in the correct direction?
I searched plenty... I had no luck with mapping... or "find" nor extracting the data I need.
My code:
function checkMeetCode(meetCode, index, searchDate) {
var ss=SpreadsheetApp.getActive().getSheetByName('AsistenciaMeet');
var colB = ss.getRange("D3:D").getValues();
var filasLlenasLengthB = colB.filter(String).length; //
var userKey = 'all';
var applicationName = 'meet';
var emailAddress = colB[index];
Logger.log("Index / Alumno: "+index+" / " + emailAddress);
var optionalArgs = {
event_name: "call_ended",
endTime: searchDate,
startTime: fechaRestada(searchDate),
filters: "identifier==" + emailAddress + ",meeting_code==" + meetCode
};
var response = AdminReports.Activities.list(userKey, applicationName, optionalArgs)
Logger.log("RESPONSE: "+response);
var actividad = response.items;
if (actividad == null) {
// do nothing
}
else {
**// HERE IS WHERE I AM TRYING TO FIND / EXTRACT INFORMATION FROM "response"
// READ BELOW PLEASE.**
}
}
NEED HELP WITH:
I want to FIND/EXTRACT the intValue of "duration_seconds":
The results from:
Logger.log("RESPONSE: "+response);
RESPONSE: {"kind":"admin#reports#activities","etag":"\"JDMC8884sebSctZ17CIssbQ/IhilrSKVziEhoZ7URUpQ-NrztHY\"","items":[{"events":[{"parameters":[{"name":"video_send_seconds","intValue":"1829"},{"name":"screencast_recv_packet_loss_mean","intValue":"0"},{"name":"identifier_type","value":"email_address"},{"name":"video_send_packet_loss_max","intValue":"0"},{"name":"endpoint_id","value":"meet_android_4154513448557872"},{"name":"video_recv_long_side_median_pixels","intValue":"320"},{"name":"calendar_event_id","value":"44jr4vu3qo75q6bvkknq_20200421T213000Z"},{"name":"video_send_fps_mean","intValue":"29"},{"name":"video_recv_short_side_median_pixels","intValue":"180"},{"name":"network_estimated_download_kbps_mean","intValue":"351"},{"name":"duration_seconds","intValue":"1830"},{"name":"video_send_bitrate_kbps_mean","intValue":"762"},{"name":"network_recv_jitter_msec_max","intValue":"130"},{"name":"ip_address","value":"186.59.21.55"},{"name":"audio_send_seconds","intValue":"1829"},{"name":"screencast_recv_packet_loss_max","intValue":"0"},{"name":"video_recv_seconds","intValue":"1818"},{"name":"network_rtt_msec_mean","intValue":"36"},{"name":"video_send_long_side_median_pixels","intValue":"640"},{"name":"screencast_recv_seconds","intValue":"1829"},{"name":"product_type","value":"meet"},{"name":"video_recv_packet_loss_max","intValue":"0"},{"name":"is_external","boolValue":false}],"name":"call_ended","type":"call"}] ...
OK, after roughly 8 hours... I was able to make it work.
var insideParameters = response["items"][0]["events"][0]["parameters"];
Logger.log(insideParameters.length);
for (var i = 30; i<insideParameters.length;i++){ // its always located above i = 30...
if(insideParameters[i].name === "duration_seconds"){
var duration = insideParameters[i].intValue;
Logger.log(duration);
}
}

Trouble populating Mongo Database from Nodejs

The following json order has shipping, payment, orderProduct as elements. I am trying to access the individual elements using the code below:
{
"shipping": "{\"nickName\":\"gsfsdfdf\",\"firstName\":\"gsfsdfdf\",\"lastName\":\"gsfsdfdf\",\"addressLine1\":\"gsfsdfdf\",\"addressLine2\":\"gsfsdfdf\",\"city\":\"gsfsdfdf\",\"country\":\"gsfsdfdf\",\"province\":\"gsfsdfdf\",\"postalCode\":\"gsfsdfdf\",\"phone\":\"gsfsdfdf\",\"email\":\"gsfsdfdf\",\"shippingInstruction\":\"gsfsdfdfgsfsdfdfgsfsdfdfgsfsdfdf\"}",
"payment": "{\"cardType\":\"Visa\",\"cardNumber\":\"11111111111111111111\",\"expMonth\":\"3\",\"expYear\":\"2019\",\"csc\":\"111\"}",
"orderProduct": "[{\"productId\":\"594fce45734d1d24b915a41f\",\"quantity\":1}]",
"deliveryDate": "2017-07-07T04:00:00.000Z"
}
I am using the code below to access the various elements of the json data:
router.post('/order/add', function (req, res) {
console.log('order = ' + req.body.order);
var newOrder = req.body.order;
console.log('shipping = ' + newOrder.shipping);
console.log('payment = ' + newOrder.payment);
console.log('orderProduct = ' + newOrder.orderProduct);
console.log('deliveryDate = ' + newOrder.deliveryDate);
var order = new Order({
shipping: newOrder.shipping,
payment: newOrder.payment,
orderProduct: newOrder.orderProduct,
deliveryDate: newOrder.deliveryDate,
});
console.log("created server order = " + order);
return res.json(200, order);
})
But the shipping, payment, orderProduct, deliveryDAte are return undefined.

how to get ng-admin filters working with loopback API

I am new to ng-admin and angularjs. I am trying to integrate ng-admin with loopback for admin panel.
I am unable to get ng-filters filters working with loopback
because of this i think the reference_list and other filter are not working properly.
The problem is that i am unable to include where filter in my request to api
i am trying to do it using restangular
below is the code
// custom filters
if (params._filters) {
for (var filter in params._filters) {
params['filter[where]'] = "{" + entry.field + ":" + rams._filters[filter] + "}";
}
delete params._filters;
}
for "where" filter can be something like this:
for(var entry in params._filters) {
if (params._filters[entry] !== undefined) {
if (params._filters[entry].constructor === Array && params._filters[entry].length > 1) { // where value in array of values
params['filter[where][' + entry + '][inq]'] = params._filters[entry];
}
else { // where entry = value
params['filter[where][' + entry + ']'] = params._filters[entry];
}
}
}
Here's my entire interceptor for handling paging, sorting and filtering with loopback. Hope it saves someone time. Note that filters on relational fields ending with 'id' are processed using equality, whereas filters on other fields use 'like'.
myApp.config(['RestangularProvider', function (RestangularProvider) {
RestangularProvider.addFullRequestInterceptor(function(element, operation, what, url, headers, params) {
if (operation == "getList") {
// custom pagination params
if (params._page) {
params["filter[skip]"]= (params._page - 1) * params._perPage;
params["filter[limit]"] = params._perPage;
}
delete params._page;
delete params._perPage;
// custom sort params
if (params._sortField) {
params["filter[order]"] = params._sortField + " " + (params._sortDir || 'ASC');
delete params._sortField;
delete params._sortDir;
}
// custom filters
if (params._filters) {
var filterClause = "";
var i = 0;
for (var filter in params._filters) {
if (filter.endsWith('id')) {
params["filter[where][and][" + i + "][" + filter + "]"] = params._filters[filter];
} else {
params["filter[where][and][" + i + "][" + filter + "][like]"] = '%' + params._filters[filter] + '%';
}
i++;
}
delete params._filters;
}
}
return { params: params };
});
}]);

Resources