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<e=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<e=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.