Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: throw promise rejections on server errors #45

Merged
merged 2 commits into from
Jun 18, 2023
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
21 changes: 21 additions & 0 deletions src/user/getUserSummary.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,27 @@ describe("Function: getUserSummary", () => {
// ASSERT
expect(response).toEqual(mockExpectedSummaryValue);
});

it("given the API returns a 503, throws an error", async () => {
// ARRANGE
const authorization = buildAuthorization({
userName: "mockUserName",
webApiKey: "mockWebApiKey"
});

const mockResponse = "<html><body>the api is down</body></html>";

server.use(
rest.get(`${apiBaseUrl}/API_GetUserSummary.php`, (_, res, ctx) =>
res(ctx.status(503), ctx.body(mockResponse))
)
);

// ASSERT
await expect(
getUserSummary(authorization, { userName: "WCopeland" })
).rejects.toThrow();
});
});

const mockGetUserSummaryResponse: GetUserSummaryResponse = {
Expand Down
17 changes: 17 additions & 0 deletions src/utils/internal/call.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,4 +36,21 @@ describe("Util: call", () => {
expect(response).toEqual({ foo: "bar" });
expect(receivedMethod).toEqual("GET");
});

it("given the call returns an error, throws an error", async () => {
// ARRANGE
const mockRequestUrl = "https://abc.xyz/v1/endpoint2";

server.use(
rest.get(mockRequestUrl, (req, res, ctx) => {
return res(
ctx.status(503),
ctx.text("<HTML><BODY>something bad happened</BODY></HTML>")
);
})
);

// ASSERT
await expect(call({ url: mockRequestUrl })).rejects.toThrow();
});
});
7 changes: 7 additions & 0 deletions src/utils/internal/call.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,5 +25,12 @@ export const call = async <
const { url } = config;

const rawResponse = await unfetch(url);

if (!rawResponse.ok) {
throw new Error(
`HTTP Error: Status ${rawResponse.status} ${rawResponse.statusText}`
);
}

return (await rawResponse.json()) as T;
};