The problem:
- I have more than 30 functions (and growing) that make REST calls to various API endpoints.
- I keep all of these functions in one large file.
- These functions follow a similar pattern of making a fetch() and passing url, body etc.
Question
I would like to achieve some degree of abstraction to lessen the amount of code and use some modern design patterns that would help me in the long run. What should I preferably do to achieve this?
- Should I use class-based architecture and JS
Class
, and if so, how? - Should I make use of core JS with
Function.prototype.call
,Function.prototype.apply
orFunction.prototype.bind
, and if so, how? - Is there some other method by which I can achieve it? Any tips and illustrative examples are greatly appreciated.
Examples of functions
Here is a flavour of the different functions that I am working with.
Note, in the fetch function I am already passing an instance of a class called RequestInit
to lessen the amount of boilerplate code.
Simple function without parameters:
export async function getLocale() {
const url = endpoints.LOCALE_URL;
try {
const response = await fetch(url, new RequestInit(Method.Get));
return response;
} catch (error) {
throw new Error(
`There was an error fetching locale.\n${error}`
);
}
}
Function with parameter as fetch body:
export async function getLikes(params: LikeParams): Promise<Response> {
if (Array.isArray(params.like_types)) {
params.like_types = params.like_types.join(",");
}
const url = endpoints.LIKES_URL;
const body = params;
try {
const response = await fetch(url, new RequestInit(Method.Get, body));
return response;
} catch (error) {
throw new Error(
`There was an error fetching likes.\n${error}`
);
}
}
Function with parameter as url path:
export async function getAsset(symbol: string): Promise<Response> {
const url = `${endpoints.ASSETS_URL}/${symbol}`;
try {
const response = await fetch(url, new RequestInit(Method.Get));
return response;
} catch (error) {
throw new Error(
`There was an error fetching asset information for ${symbol}.\n${error}`
);
}
}