loopback icon indicating copy to clipboard operation
loopback copied to clipboard

filter parameters in GET requests

Open leonidasKap opened this issue 12 years ago • 1 comments

In version 2.0, I am using the memory connector and my model looks as follows:

instance { id (number, optional), os (string), location (string), business_area (string), version (string) }

I am also building queries in the form of json objects to pick certain entries. An example query can be like: var query = { "where":{ "and":[ { "and":[ { "or":[ { "os":"Linux" }, { "os":"Solaris" }, { "os":"AIX" } ] }, { "os":{ "nlike":"Windows" } } ] } ] } }

I submit the query via

$.ajax({ url : 'api/instances', type: 'GET', data: {filter : query}, contentType : 'application/json', });

Jquery uses http://api.jquery.com/jQuery.param/ to process the whole query into a URL that looks like:

http://localhost:3000/api/probes?filter[where][and][0][and][0][or][0][os]=Linux&filter[where][and][0][and][0][or][1][os]=Solaris&filter[where][and][0][and][0][or][2][os]=AIX&filter[where][and][0][and][1][os][nlike]=Windows

which gets url encoded. (use this http://www.url-encode-decode.com/urlencode to see the final product)

Given the entries in my connector This query should return everything apart from instances where "os" is Windows, but it returns an empty array instead.

In order to make it work, I ended up stringifying the query object and urlencoding it before passing to ajax. This is what the swagger ui does. var queryString = "filter="+encodeURIComponent(JSON.stringify(query)); var dataPromise = $.ajax({ url : this.resource, type: 'GET', data: queryString, contentType : 'application/json', }); Is there a better way ? Ideally, I don't want to do manual encoding.

I also remember URLs like http://localhost:3000/api/probes?filter[where][and][0][and][0][or][0][os]=Linux&filter[where][and][0][and][0][or][1][os]=Solaris&filter[where][and][0][and][0][or][2][os]=AIX&filter[where][and][0][and][1][os][nlike]=Windows to be working in an earlier loopback.io version. I can't pinpoint the exact version but it was later than 1.7 and earlier than 2.0

leonidasKap avatar Sep 02 '14 14:09 leonidasKap

LoopBack accepts two styles at the backend:

  1. stringified json for the filter object
  2. Use qs module to encode the filter object (see https://github.com/hapijs/qs)

raymondfeng avatar Sep 02 '14 15:09 raymondfeng