Skip to content
Open
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
18 changes: 9 additions & 9 deletions src/shared/api/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@ import ky, {
HTTPError,
KyInstance,
Options as KyOptions,
KyRequest,
KyResponse,
NormalizedOptions,
TimeoutError,
} from "ky";
import { API_URL, getAccessToken, HTTPHeaderKey } from "./config";
Expand All @@ -27,6 +30,7 @@ const defaultConfig: KyOptions = {
methods: ["get", "put", "post", "delete", "patch"],
statusCodes: [408, 413, 429, 500, 502, 503, 504],
},
throwHttpErrors: false,
};

export const publicClient = ky.create({
Expand All @@ -47,20 +51,14 @@ const refreshClient = ky.create({
retry: 0,
});

const handleHttpError = async ({
request,
response,
options,
}: HTTPError): Promise<HTTPError> => {
const handleHttpError = async (request: KyRequest, options: NormalizedOptions, response: KyResponse): Promise<HTTPError> => {
throw match(response.status)
.with(401, () => new UnauthorizedError(response, request, options))
.with(403, () => new ForbiddenError(response, request, options))
.with(404, () => new NotFoundError(response, request, options))
.with(409, () => new ConflictError(response, request, options))
.with(400, () => new BadRequestError(response, request, options))
.with(422, () => new ValidationError(response, request, options))
.with(503, () => new ServiceUnavailableError(response, request, options))
.otherwise(() => new ServerError(response, request, options));
.with(503, () => new ServiceUnavailableError(response, request, options));
};

const refreshAccessToken = async (refreshToken: string): Promise<string> => {
Expand Down Expand Up @@ -89,6 +87,9 @@ export const client = ky.create({
},
],
afterResponse: [
async (request, options, response) => {
await handleHttpError(request, options, response);
},
async (request, options, response) => {
if (response.status === 401) {
const { refreshToken, refresh } = useAuthStore.getState();
Expand All @@ -109,6 +110,5 @@ export const client = ky.create({
}
},
],
beforeError: [handleHttpError],
},
});
Loading