For a personal project I've been working on (originally started in Javascript), I needed to make http requests. To streamline this process, I opted to use Axios and created a file called http.js with the code below:
import axios from 'axios';
const baseURL = '/api';
const requestWrapper = async (request, { url, options, data }) => {
const config = { baseURL, ...options };
const requestObject = await request.apply(
this,
data ? [url, data, config] : [url, config]
);
const requestData = requestObject.data;
return { status: requestObject.status, data: requestData };
};
const get = async (url, options) => {
try {
return await requestWrapper(axios.get, { url, options });
} catch (error) {
return error.response;
}
};
// More http request functions...
export { get, remove, post, put, patch };
In the previous snippet of code, I encapsulated each http request into its own function for easy management in case the http client library changes.
Now, I aim to convert this file to Typescript. My specific hurdle lies in passing a generic T through the Axios function within the wrapper function as shown here:
const requestObject = await request.apply(
this,
data ? [url, data, config] : [url, config]
);
I am unsure how to specify the generic in this context. Any suggestions on what I should do?
I have explored various solutions but haven't found anything that directly addresses my issue. One idea I considered is removing the internal wrapper and calling each Axios function within its respective encapsulation function.