Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Apisauce interceptor

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

   return { kind: 'ok', userInfo: response.data.result };

any ideas?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading