I’ve joined a new project and I see that there are many places that duplicate axios request boilerplate code, for example the following file:
export class Api {
static sendEmail = async (mail: string) => {
const response = await axios({
method: 'post',
url: `${apiUrl}/auth/login`,
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
data: {
email: mail
}
});
return response;
};
static getAdminDashboardData = async () => {
const response = await axios({
method: 'get',
url: `${apiUrl}/admin/dashboard`,
headers: {
Authorization: `Bearer ${accessToken}`,
'Content-Type': 'application/json'
}
});
return response;
};
static getIndices = async () => {
const response = await axios({
method: 'get',
url: `${apiUrl}/admin/indices`,
headers: {
Authorization: `Bearer ${accessToken}`,
'Content-Type': 'application/json'
}
});
return response;
};
static getListHr = async () => {
const response = await axios({
method: 'get',
url: `${apiUrl}/admin/partenaires`,
headers: {
Authorization: `Bearer ${accessToken}`,
'Content-Type': 'application/json'
}
});
return response;
};
static getListProvider = async () => {
const response = await axios({
method: 'get',
url: `${apiUrl}/admin/prestataires`,
headers: {
Authorization: `Bearer ${accessToken}`,
'Content-Type': 'application/json'
}
});
return response;
};
}
So I want to create a common file for all api calls. This is what I came up with so far.
import axios from 'axios';
export default axios.create({
baseURL: 'http://localhost:8080/api',
headers: {
'Content-type': 'application/json'
}
});
I know this file should be a little more advanced, i.e. filled with more options, so maybe someone can recommend how to structure it.