From 80bb8a108f29331cdb2f2695f6801beee104dc89 Mon Sep 17 00:00:00 2001 From: MohamedBassem Date: Thu, 8 Feb 2024 15:14:23 +0000 Subject: [refactor] Move the different packages to the package subdir --- web/lib/api.ts | 81 ---------------------------------------------------------- 1 file changed, 81 deletions(-) delete mode 100644 web/lib/api.ts (limited to 'web/lib/api.ts') diff --git a/web/lib/api.ts b/web/lib/api.ts deleted file mode 100644 index 56686cde..00000000 --- a/web/lib/api.ts +++ /dev/null @@ -1,81 +0,0 @@ -"use client"; - -import { ZodTypeAny, z } from "zod"; -import { - ZNewBookmarkedLinkRequest, - zGetLinksResponseSchema, -} from "./types/api/links"; - -import serverConfig from "./config"; - -const BASE_URL = `${serverConfig.api_url}/api/v1`; - -export type FetchError = { - status?: number; - message?: string; -}; - -type InputSchema = T extends ZodTypeAny ? T : undefined; - -async function doRequest( - path: string, - respSchema?: InputSchema, - opts?: RequestInit, -): Promise< - | (InputSchema extends ZodTypeAny - ? [z.infer>, undefined] - : [undefined, undefined]) - | [undefined, FetchError] -> { - try { - const res = await fetch(`${BASE_URL}${path}`, opts); - if (!res.ok) { - return [ - undefined, - { status: res.status, message: await res.text() }, - ] as const; - } - if (!respSchema) { - return [undefined, undefined] as const; - } - - let parsed = respSchema.safeParse(await res.json()); - if (!parsed.success) { - return [ - undefined, - { message: `Failed to parse response: ${parsed.error.toString()}` }, - ] as const; - } - - return [parsed.data, undefined] as const; - } catch (error: any) { - return [ - undefined, - { message: `Failed to execute fetch request: ${error}` }, - ] as const; - } -} - -export default class APIClient { - static async getLinks() { - return await doRequest(`/links`, zGetLinksResponseSchema, { - next: { tags: ["links"] }, - }); - } - - static async bookmarkLink(url: string) { - const body: ZNewBookmarkedLinkRequest = { - url, - }; - return await doRequest(`/links`, undefined, { - method: "POST", - body: JSON.stringify(body), - }); - } - - static async unbookmarkLink(linkId: string) { - return await doRequest(`/links/${linkId}`, undefined, { - method: "DELETE", - }); - } -} -- cgit v1.2.3-70-g09d2