Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 17 additions & 12 deletions app/src/utils/fetchApi/fetchApi.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -118,36 +118,41 @@ describe("fetchApi", () => {

it("handles a Collections API 422 error for invalid param values", async () => {
const mockBadParams = { param1: "value1", param2: "value2" };
const mockResponse = { response: "mockResponse" };
const mockResponse = "mockResponse";
(global as any).fetch = jest.fn(() =>
Promise.resolve({
status: 422,
statusText: "Invalid parameter value: something something",
json: async () => mockResponse,
text: async () => mockResponse,
})
) as jest.Mock;

const response = await fetchApi({
apiUrl: mockApiUrl,
options: {
isRepoApi: false,
params: mockBadParams,
},
});

expect(response).toEqual(mockResponse);
await expect(
fetchApi({
apiUrl: mockApiUrl,
options: {
isRepoApi: false,
params: mockBadParams,
},
})
).rejects.toEqual(
new Error(
"Error fetching mockurl.org?param1=value1&param2=value2: 422 mockResponse"
)
);
});

it("throws an error for non-200 status", async () => {
(global as any).fetch = jest.fn(() =>
Promise.resolve({
status: 500,
statusText: "Internal Server Error",
text: async () => "Bad things happened",
})
) as jest.Mock;

await expect(fetchApi({ apiUrl: mockApiUrl })).rejects.toEqual(
new Error("fetchApi: 500 Internal Server Error")
new Error(`Error fetching ${mockApiUrl}: 500 Bad things happened`)
);
});

Expand Down
22 changes: 10 additions & 12 deletions app/src/utils/fetchApi/fetchApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,26 +71,24 @@ export const fetchApi = async ({
]);
};

let response: Response;
try {
const response = (await fetchWithTimeout(apiUrl, {
response = (await fetchWithTimeout(apiUrl, {
method,
headers: headers,
body: method === "POST" ? JSON.stringify(body) : undefined,
next,
})) as Response;

if (response.status === 422) {
logger.error(`Invalid parameter value: ${apiUrl}`);
} else if (!response.ok) {
throw new Error(
`fetchApi: ${response.status} ${
response.statusText ? response.statusText : "No message"
}`
);
}
return await response.json();
} catch (error) {
logger.error(error);
throw new Error(error.message);
}
if (response.ok) {
return await response.json();
}
const responseText = await response.text();

throw new Error(
`Error fetching ${apiUrl}: ${response.status} ${responseText}`
);
};