diff options
| author | MohamedBassem <me@mbassem.com> | 2024-02-11 14:54:52 +0000 |
|---|---|---|
| committer | MohamedBassem <me@mbassem.com> | 2024-02-11 14:55:09 +0000 |
| commit | 2c2d05fd0a2c3c26d765f8a6beb88d907a097c1d (patch) | |
| tree | c4738ba0bc011d60361f89aca9be3293474ab9e9 /packages/web/lib/api.ts | |
| parent | c2f1d6d8b8a0f09820153fc736806b147d46abfe (diff) | |
| download | karakeep-2c2d05fd0a2c3c26d765f8a6beb88d907a097c1d.tar.zst | |
refactor: Migrating to trpc instead of next's route handers
Diffstat (limited to 'packages/web/lib/api.ts')
| -rw-r--r-- | packages/web/lib/api.ts | 91 |
1 files changed, 0 insertions, 91 deletions
diff --git a/packages/web/lib/api.ts b/packages/web/lib/api.ts deleted file mode 100644 index 3978dcb6..00000000 --- a/packages/web/lib/api.ts +++ /dev/null @@ -1,91 +0,0 @@ -"use client"; - -import { ZodTypeAny, z } from "zod"; -import { - ZNewBookmarkRequest, - ZUpdateBookmarksRequest, - zBookmarkSchema, - zGetBookmarksResponseSchema, -} from "./types/api/bookmarks"; - -import serverConfig from "./config"; - -const BASE_URL = `${serverConfig.api_url}/api/v1`; - -export type FetchError = { - status?: number; - message?: string; -}; - -type InputSchema<T> = T extends ZodTypeAny ? T : undefined; - -async function doRequest<T>( - path: string, - respSchema?: InputSchema<T>, - opts?: RequestInit, -): Promise< - | (InputSchema<T> extends ZodTypeAny - ? [z.infer<InputSchema<T>>, 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; - } - - const 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) { - return [ - undefined, - { message: `Failed to execute fetch request: ${error}` }, - ] as const; - } -} - -export default class APIClient { - static async getBookmarks() { - return await doRequest(`/bookmarks`, zGetBookmarksResponseSchema, { - next: { tags: ["links"] }, - }); - } - - static async bookmarkLink(url: string) { - const body: ZNewBookmarkRequest = { - type: "link", - url, - }; - return await doRequest(`/bookmarks`, undefined, { - method: "POST", - body: JSON.stringify(body), - }); - } - - static async deleteBookmark(id: string) { - return await doRequest(`/bookmarks/${id}`, undefined, { - method: "DELETE", - }); - } - - static async updateBookmark(id: string, update: ZUpdateBookmarksRequest) { - return await doRequest(`/bookmarks/${id}`, zBookmarkSchema, { - method: "PATCH", - body: JSON.stringify(update), - }); - } -} |
