Variable in "where" filter with Axios and Loopback

Viewed 4525

I'm in trouble to use variables in an Axios request to a Loopback(v3) API.

What works? If I use the "REST notation" it works well:

 getInfo() {
   axios.get('http://myIp/api/tabs?filter[where][name]=' + this.name).then(response => {
     this.tabs = response.data
})

What doesn't work yet:

I can't translate the "REST notation" to the "Node notation" that I would prefer to use here.

What I tried already:

axios.get('http://myIp/api/tabs?filter={"where":{"name": this.name }}).then(response => {
        this.tabs = response.data  
})

I realise that with single quotes around the whole request, I can't get variable interpolation. But if I use double quotes, I don't know how to escape the ones used for the reserved words like "where", ...

What would be the correct way to use variables in this context?

4 Answers

Try:

axios.get('http://myIp/api/tabs').then(response => {
     this.tabs = response.data.filter(b => b.name === this.name)

It should work. the main trick is response.data.filter() then give your filter logic inside the filter().

I suggest to run something like this:

let value = "John";

let filter = {
   where: {
     name: value
   }
};
axios.get('http://myIp/api/tabs?filter=' + JSON.stringify(filter)).then(response => {
   this.tabs = response.data  
});

This way you will be sure that object is constructed in a proper way and you won't pass full object into the request, also you won't get lost with opening and closing brackets/parentheses

ok, I will try to split this in smaller chunks and I need to add another answer to that becasue it's too long for a comment:

  1. axios.get

axios.get('http://myIp/api/tabs?filter=' + JSON.stringify(filter)).then(response => { ... });

This expects a url as a string. since it's GET request, you cannot pass variables in the different form than in request url as variables, eg. http://mypage.com?variable1=value1&variable2=value2

  1. argument

axios.get('http://myIp/api/tabs?filter=' + JSON.stringify(filter)).then(response => { this.tabs = response.data
});

Making super complicated urls can be a bit frustrating and not readable. fortunately, in loopback you can pass in an object instead. but to do this in the GET request, you need to pass it as a string. So you can call JSON.stringify on the object to make it a string.

  1. concatenation

axios.get('http://myIp/api/tabs?filter=' + JSON.stringify(filter)).then(response => { this.tabs = response.data
});

Then, to pass that into URL you can concatenate your url with filter object stringified, like this:

# one method
url + JSON.stringify(filter)

# another method
var filters = JSON.stringify(filter);
axios.get(`http://myapi.com?filter=${filters}`, function(...))

Hopefully that helps

axios.get('http://myIp/api/tabs?filter={"where":{"name":'+this.name }})
  .then(response => {
     this.tabs = response.data  
Related