I have this code that is building a url endpoint taking in different parameters:
const query = (obj) => {
let starter = 'query='
let queryToString = JSON.stringify(obj)
return `${starter}${queryToString}`
}
const params = (str) => `${str}`
const endpoint = (protocol, base, params, query) => {
if (!params && !query) return `${base}`
if (!params) return `${base}${query}`
return `${protocol}${base}?${params}&${query}`
}
const baseUrl = 'api.content.io'
const protocol = (secure = true) => secure ? 'https://' : 'http://'
let result = endpoint(protocol(), baseUrl, params('limit=5&order=desc'),
query({
field: 'title',
include: 'brands'
}));
console.log(result)
This builds a string like:
https: //api.content.io?limit=5&order=desc&query={"field":"title","include":"brands"}
Is it possible to refactor this code such that the conditionals inside the endpoint
function can be removed, the right concatenation strings be applied and the whole thing chained into a functional call like
Endpoint.chain(protocol(p)).chain(base(b)).chain(params(p)).chain(query(q)).build()
How do I get started with doing this?
UPDATE: The solutions below are pretty good but I would like to understand how functional programmers use ADTs (Algebraic Data Types) with Monads to solve this problem. The idea is to run a chain
of functions and then a fold
to get back the value I want
Although the above answers will work, but if you want the syntax to start with
Endpoint().
then use a class EndpointBuilder and a factory function like below.Usage Example: