How can I simplify this code to use conditional method chaining for useBuffer() method. Please suggest.
const getApi = async (headers, userContext, httpRequest, url, isBlob) => {
if (isBlob) {
const result = await httpRequest
.get(url)
.withCredentials()
.set(headers)
.send({ userContext })
.useBuffer()
.then((res) => [res.body, res.headers]);
return result;
}
else {
const result = await httpRequest
.get(url)
.withCredentials()
.set(headers)
.send({ userContext })
.then((res) => res);
return result;
}
};
to something like this:
const getApi = async (headers, userContext, httpRequest, url, isBlob) => {
const result = await httpRequest
.get(url)
.withCredentials()
.set(headers)
.send({ userContext })
.isBlob && useBuffer()
.then((res) => isBlob ? [res.body, res.headers] : res);
return result;
};
.then((res) => res)
is redundant and boolean parameters that control structure are questionable design, so how about:
const getApi = (headers, userContext, httpRequest, url) =>
httpRequest
.get(url)
.withCredentials()
.set(headers)
.send({ userContext });
const getApiBlob = (headers, userContext, httpRequest, url) =>
getApi(headers, userContext, httpRequest, url)
.useBuffer()
.then((res) => [res.body, res.headers]);