Skip to content

Commit

Permalink
refactor: better handling timeouts and aborting tcp connection (#7017)
Browse files Browse the repository at this point in the history
* refactor: better handling timeouts and aborting tcp connection

* refactor: created object with connection errors
  • Loading branch information
Fifciu authored Feb 6, 2024
1 parent c3349d1 commit c4534b5
Show file tree
Hide file tree
Showing 4 changed files with 43 additions and 2 deletions.
5 changes: 5 additions & 0 deletions .changeset/poor-tips-appear.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@vue-storefront/middleware": patch
---

Adjusted handling timeouts and aborting TCP connection
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,28 @@ describe("[middleware-helpers] getAgnosticStatusCode", () => {
expect(statusCode).toBe(defaultCode);
});

it("retrieves status code for axios even when status code is missing and it's timeout", () => {
const testData = {
isAxiosError: true,
code: "ECONNABORTED",
};

const statusCode = getAgnosticStatusCode(testData);

expect(statusCode).toBe(408);
});

it("retrieves status code for axios even when status code is missing and recipient closed TCP connection", () => {
const testData = {
isAxiosError: true,
code: "ECONNRESET",
};

const statusCode = getAgnosticStatusCode(testData);

expect(statusCode).toBe(500);
});

it("retrieves status code for apollo when code is a string", () => {
const testData = {
code: "someString",
Expand Down
15 changes: 14 additions & 1 deletion packages/middleware/src/helpers/getAgnosticStatusCode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,15 @@ import {
} from "../types";

const STATUS_FIELDS = ["status", "statusCode"] as const;
/**
* @key is constant string identifier of connection error
* @value is desired HTTP code that we are going to
* send back when we encounter specified connection error
*/
const CONNECTION_ERRORS = {
ECONNABORTED: 408,
ECONNRESET: 500,
};

export type Status = (typeof STATUS_FIELDS)[number];

Expand Down Expand Up @@ -58,7 +67,11 @@ function obtainStatusCode(
}

function getAxiosStatusCode(error: AxiosError) {
return error.response?.status ?? 500;
if (error?.code && CONNECTION_ERRORS[error.code]) {
return CONNECTION_ERRORS[error.code];
}

return error.response?.status;
}

function getApolloStatusCode(error: ApolloError) {
Expand Down
3 changes: 2 additions & 1 deletion packages/middleware/src/types/base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,8 @@ export type ApiClientMethods<T> = {

export type AxiosError = {
isAxiosError: boolean;
response: {
code: string;
response?: {
status: number;
};
};
Expand Down

0 comments on commit c4534b5

Please sign in to comment.