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;
};
How about saving the earlier chain in a variable?
const getApi = async (headers, userContext, httpRequest, url, isBlob) => {
const sent = await httpRequest
.get(url)
.withCredentials()
.set(headers)
.send({ userContext })
return !isBlob
? sent
: sent
.useBuffer()
.then((res) => [res.body, res.headers]);
};
The .then((res) => res);
is completely superfluous and so can be removed.
.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]);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.