From 32ccbd11449ccbec747357e9baa1ce3d31af0274 Mon Sep 17 00:00:00 2001 From: wescopeland Date: Sat, 17 Jun 2023 07:42:46 -0400 Subject: [PATCH 1/2] fix: throw promise rejections on server errors --- src/user/getUserSummary.test.ts | 20 ++++++++++++++++++++ src/utils/internal/call.test.ts | 17 +++++++++++++++++ src/utils/internal/call.ts | 7 +++++++ 3 files changed, 44 insertions(+) diff --git a/src/user/getUserSummary.test.ts b/src/user/getUserSummary.test.ts index 4a9121c..05fa8cf 100644 --- a/src/user/getUserSummary.test.ts +++ b/src/user/getUserSummary.test.ts @@ -44,6 +44,26 @@ 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 = "the api is down"; + + server.use( + rest.get(`${apiBaseUrl}/API_GetUserSummary.php`, (_, res, ctx) => + res(ctx.status(503), ctx.body(mockResponse)) + ) + ); + + await expect( + getUserSummary(authorization, { userName: "WCopeland" }) + ).rejects.toThrow(); + }); }); const mockGetUserSummaryResponse: GetUserSummaryResponse = { diff --git a/src/utils/internal/call.test.ts b/src/utils/internal/call.test.ts index d83e082..40a6ee1 100644 --- a/src/utils/internal/call.test.ts +++ b/src/utils/internal/call.test.ts @@ -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("something bad happened") + ); + }) + ); + + // ASSERT + await expect(call({ url: mockRequestUrl })).rejects.toThrow(); + }); }); diff --git a/src/utils/internal/call.ts b/src/utils/internal/call.ts index 5b5f6b2..8d8388c 100644 --- a/src/utils/internal/call.ts +++ b/src/utils/internal/call.ts @@ -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; }; From fe4c074bbdb933431210d46af9a4412bb89a617a Mon Sep 17 00:00:00 2001 From: wescopeland Date: Sat, 17 Jun 2023 07:45:23 -0400 Subject: [PATCH 2/2] chore: add missing comment --- src/user/getUserSummary.test.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/src/user/getUserSummary.test.ts b/src/user/getUserSummary.test.ts index 05fa8cf..eb62a12 100644 --- a/src/user/getUserSummary.test.ts +++ b/src/user/getUserSummary.test.ts @@ -60,6 +60,7 @@ describe("Function: getUserSummary", () => { ) ); + // ASSERT await expect( getUserSummary(authorization, { userName: "WCopeland" }) ).rejects.toThrow();