Home > database >  Apisauce interceptor
Apisauce interceptor

Time:11-25

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?

CodePudding user response:

The only thing that changes is the endpoint. How about making another function around api.post that takes the endpoint as a parameter?

const getAPI = async (endpoint: string) => {
  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 };
}

And then your first snippet simplifies to

return getAPI('endpoint1');

and your second snippet to

return getAPI('endpoint2');

and so on.

If reqBody changes, add it as a parameter too.

  • Related