API request using tagged template literals
javascripttemplateliteralsI recently came across this awesome video introducing tagged template literals. At the end of the video @kentcdodds does talk about possible use case with API request with something like this.
const response = await GET`https://dev.to`;
console.log(response.text());
So here it is a rudimentary implementation for that
function GET(literalStrings, ...interpolations) {
const URL = literalStrings[0];
let headers = {
METHOD: 'GET',
};
if (interpolations.length === 1) {
headers = { ...headers, ...JSON.parse(interpolations[0]) };
}
return fetch(URL, headers);
}
you can use this as follows
const headers = JSON.stringify({
cretentials: 'include',
});
const response = await GET`https://dev.to ${headers}`;
console.log(response.text());
Similarly you can write POST, PUT and DELETE too (with third stringified argument as request body it if is present).
So why do you want something like this ?
- It might be easy to mock the fetch functions while testing by importing mock GET function (argument can be made against this)
- It is easier to test the request made since it is just a string
- It looks pretty
If the implementation was not dependent on fetch API it could be used in other environments like node (if you did not have node-fetch).
This post is also available on DEV.