1

In my application, I have to accept certain user parameters like limit and query and progressively build a restful api endpoint.

This code works:

const query = (obj) => {
  let starter = 'query='
  let queryToString = JSON.stringify(obj)
  return `${starter}${queryToString}`
}

const params = (str) => `${str}`

const endpoint = (base, params, query) => {
  if(!params && !query) return `${base}`
  if(!params) return `${base}${query}`
  return `${base}?${params}&${query}`
}

When I call the endpoint function, I get the output I want which is:

"api.content.io?limit=5&order=desc&query={\"field\":\"title\",\"include\":\"brands\"}"

Problem is I have to account for multiple scenarios where

a. no params are passed in

b. no query is passed in

c. only params or query is passed in

d. additional query parameters and other parameters are appended at a later point in the program

What I am looking for is a compositional style function that maybe looks like this:

const apiEndpoint = endpoint(params(query(value))))

...and then these individual functions magically take care of both concatenating the different outputs, url-encoding the string and handling null values to give me a clean valid output.

As you can see above, I have tried splitting the code into multiple functions with single responsibilities. But can't figure out how to compose them. The expected output is

api.contentstack.io?field=name&lte=price&query={limit: 5, order: 'desc')}

or if params are not passed then:

api.contentstack.io?query={limit: 5, order: 'desc')}

else if query is not passed then:

api.contentstack.io?field=name&lte=price

and so on...

Please help me understand how I can refactor and compose my functions so I can remove the conditional checks inside the endpoint function.

Amit Erandole
  • 11,995
  • 23
  • 65
  • 103
  • Why don't you try chaining the functions ? – gvmani Dec 30 '16 at 05:45
  • What is expected result for each and all of the multiple scenarios occurring? – guest271314 Dec 30 '16 at 05:46
  • a string like this: "api.contentstack.io?field=name&lte=price&query={limit: 5, order: 'desc')}" – Amit Erandole Dec 30 '16 at 05:47
  • fwiw, trying to achieve a similar pattern to `endpoint(params(query(value))))` at [How to call function that is parameter to Function.prototype.bind with value passed as parameter to Function.prototype.bind](http://stackoverflow.com/questions/40541169/how-to-call-function-that-is-parameter-to-function-prototype-bind-with-value-pas), though different expected result. Where function and parameter passed to `.bind()` and function should be called with parameter passed; e.g., `result(1, isOne.bind(null, compare.bind(null, value)))`. Have yet to successfully get expected result. – guest271314 Dec 30 '16 at 05:53

0 Answers0