Skip to content

Commit

Permalink
refactor: WT-2041 - better axios response handling (#1336)
Browse files Browse the repository at this point in the history
  • Loading branch information
andrearampin authored Jan 15, 2024
1 parent 3f88b62 commit 03f56f5
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 16 deletions.
10 changes: 4 additions & 6 deletions packages/checkout/sdk/src/availability/availability.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,8 @@ describe('availabilityService', () => {
});

describe('checkDexAvailability', () => {
it('should return true when status is 204', async () => {
const mockResponse = {
status: 204,
};
it('should return true when status is 2xx', async () => {
const mockResponse = {};
mockedAxios.post.mockResolvedValueOnce(mockResponse);
const response = await availabilityService(true, false).checkDexAvailability();

Expand All @@ -26,7 +24,7 @@ describe('availabilityService', () => {
const mockResponse = {
status: 403,
};
mockedAxios.post.mockResolvedValueOnce(mockResponse);
mockedAxios.post.mockRejectedValueOnce({ response: mockResponse });
const response = await availabilityService(true, false).checkDexAvailability();

expect(mockedAxios.post).toHaveBeenCalledTimes(1);
Expand All @@ -38,7 +36,7 @@ describe('availabilityService', () => {
status: 500,
statusText: 'error message',
};
mockedAxios.post.mockResolvedValueOnce(mockResponse);
mockedAxios.post.mockRejectedValueOnce({ response: mockResponse });

await expect(availabilityService(true, false).checkDexAvailability())
.rejects
Expand Down
21 changes: 11 additions & 10 deletions packages/checkout/sdk/src/availability/availability.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,19 +24,20 @@ export const availabilityService = (
try {
response = await axios.post(`${postEndpoint()}/v1/availability/checkout/swap`);
} catch (error: any) {
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
response = error.response;
}

if (response.status === 403) {
return false;
}
if (response.status === 204) {
return true;
// If 403 then the service is geo-blocked
if (response.status === 403) return false;

throw new CheckoutError(
`Error fetching from api: ${response.status} ${response.statusText}`,
CheckoutErrorType.API_ERROR,
);
}
throw new CheckoutError(
`Error fetching from api: ${response.status} ${response.statusText}`,
CheckoutErrorType.API_ERROR,
);

return true;
};

return {
Expand Down

0 comments on commit 03f56f5

Please sign in to comment.