moses toh
moses toh

Reputation: 13172

How can I make dynamic parameter on the url?

My url like this :

https://my-website.com/api/players?countryId=1&clubId=2&playerName=abc

The parameter is dynamic

My code like this :

getDataPlayer(payload) {
    let params
    if(payload.countryId && payload.clubId && payload.playerName)
      params = `countryId=${payload.countryId}&clubId=${payload.clubId}&playerName=${payload.playerName}`

    return axios.get(`https://my-website.com/api/players?${params}`)
      .then(response => {
        return response.data
      })
},

If I console.log(payload), the result like this :

{countryId: "1", clubId: "2", playerName: "ronaldo"}

It's dynamic. The payload can be :

{countryId: "1", clubId: "2"} or

{playerName: "ronaldo"}

Is there a simple way? or I have to make a lot of conditions in method getDataPlayer

Upvotes: 0

Views: 938

Answers (3)

chans
chans

Reputation: 5260

function formatQuery(payload) {
  var params = '';

  if (payload.countryId && payload.countryId.trim().length) params += `countryId=${encodeURIComponent(payload.countryId.trim())}&`;

  if (payload.clubId && payload.clubId.trim().length) params += `clubId=${encodeURIComponent(payload.clubId.trim())}&`;

  if (payload.playerName && payload.playerName.trim().length) params += `playerName=${encodeURIComponent(payload.playerName.trim())}`;


  console.log(params);
  return params;

}

formatQuery({countryId: "1", clubId: "2", playerName: "ronaldo"});

formatQuery({countryId: "1", clubId: "2"});

formatQuery({playerName: "ronaldo"});

Upvotes: -1

Linh Nguyen
Linh Nguyen

Reputation: 947

For query string parameter, you can use encodeURIComponent to encode the string correctly. Use Array.map to loop over the keys and combine final result by Array.join like this

 let params = Object.keys(payload).map(el => `${el}=${encodeURIComponent(payload[el])}`).join('&')

If your payload is {countryId: "1", clubId: "2", playerName: "ronal do "} the params become "countryId=1&clubId=2&playerName=ronal%20do%20" and it is passed to request correctly

Upvotes: 2

Gautam
Gautam

Reputation: 108

If you so wish, you can use the npm module query-string. Link: https://www.npmjs.com/package/query-string.

You can then convert a JSON object directly into well formed search params. It provides functionality to encode as well.

Upvotes: 0

Related Questions