Recently i had to rewrite all of my API calls with Apisauce, is amazing but i have very repeating code which looks like this:
const response: ApiResponse<{ result: ReponseType }> = await api.post('endpoint1', reqBody);
if (!response.ok || !response.data) {
return getGeneralApiProblem(response);
}
return { kind: 'ok', userInfo: response.data.result };
const response: ApiResponse<{ result: ReponseType }> = await api.post('endpoint2', reqBody);
if (!response.ok || !response.data) {
return getGeneralApiProblem(response);
}
return { kind: 'ok', userInfo: response.data.result };
const response: ApiResponse<{ result: ReponseType }> = await api.post('endpoint3', reqBody);
if (!response.ok || !response.data) {
return getGeneralApiProblem(response);
}
return { kind: 'ok', userInfo: response.data.result };
How i can extract this part
if (!response.ok || !response.data) {
return getGeneralApiProblem(response);
}
or maybe even this one as well:
return { kind: 'ok', userInfo: response.data.result };
any ideas?
The only thing that changes is the endpoint. How about making another function around
api.post
that takes the endpoint as a parameter?And then your first snippet simplifies to
and your second snippet to
and so on.
If
reqBody
changes, add it as a parameter too.