Skip to content

Commit

Permalink
Refactor isErrorCode util into api utils
Browse files Browse the repository at this point in the history
  • Loading branch information
allanlasser committed Apr 17, 2024
1 parent 892a5bf commit b2e70e8
Show file tree
Hide file tree
Showing 4 changed files with 13 additions and 9 deletions.
2 changes: 1 addition & 1 deletion src/lib/api/projects.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import type { Project, ProjectResults, ProjectMembershipList } from "./types";

import { error, type NumericRange } from "@sveltejs/kit";
import { BASE_API_URL } from "@/config/config.js";
import { isErrorCode } from "$lib/utils/isErrorCode";
import { isErrorCode } from "$lib/utils/api";

/**
* Get a single project
Expand Down
6 changes: 6 additions & 0 deletions src/lib/utils/isErrorCode.ts → src/lib/utils/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,9 @@ import type { NumericRange } from "@sveltejs/kit";
export function isErrorCode(status: number): status is NumericRange<400, 599> {
return status >= 400 && status <= 599;
}

export function isRedirectCode(
status: number,
): status is NumericRange<300, 308> {
return status >= 300 && status <= 308;
}
2 changes: 1 addition & 1 deletion src/lib/utils/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1 @@
export { isErrorCode } from "./isErrorCode";
export { isErrorCode, isRedirectCode } from "./api";
12 changes: 5 additions & 7 deletions src/routes/(pages)/[...path]/+page.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { gfmHeadingId } from "marked-gfm-heading-id";
import DOMPurify from "isomorphic-dompurify";

import { BASE_API_URL } from "@/config/config.js";
import { isErrorCode, isRedirectCode } from "@/lib/utils/api";

marked.use(gfmHeadingId());

Expand All @@ -16,16 +17,13 @@ export async function load({ fetch, params }) {

const resp = await fetch(endpoint, { credentials: "include" });

if (resp.status > 400) {
error(resp.status as NumericRange<400, 599>, resp.statusText);
if (isErrorCode(resp.status)) {
error(resp.status, resp.statusText);
}

// we should be following redirects, so this shouldn't happen
if (resp.status > 300) {
redirect(
resp.status as NumericRange<300, 308>,
resp.headers.get("Location"),
);
if (isRedirectCode(resp.status)) {
redirect(resp.status, resp.headers.get("Location"));
}

const page = await resp.json();
Expand Down

0 comments on commit b2e70e8

Please sign in to comment.