aboutsummaryrefslogtreecommitdiffstats
path: root/src/api.ts
diff options
context:
space:
mode:
authorJan Tuomi <jans.tuomi@gmail.com>2022-02-05 15:18:48 +0200
committerJan Tuomi <jans.tuomi@gmail.com>2022-02-05 15:18:48 +0200
commit7d78bf4d2111af87636069ee2d35d6323ffc96be (patch)
treec0d8d88e68c8d6dd92bcb2ba7e39f0ce21bc11eb /src/api.ts
parent232c1e536d22dbb46b7d11fc389695d440343495 (diff)
Get stuff running
Diffstat (limited to 'src/api.ts')
-rw-r--r--src/api.ts50
1 files changed, 50 insertions, 0 deletions
diff --git a/src/api.ts b/src/api.ts
new file mode 100644
index 0000000..7fd9e64
--- /dev/null
+++ b/src/api.ts
@@ -0,0 +1,50 @@
+import useSWR, { SWRResponse } from "swr"
+
+const API_URL = import.meta.env.VITE_API_URL
+
+const fetcher = (path: string) => fetch(`${API_URL}${path}`)
+ .then(res => res.json())
+ .catch((err) => {
+ console.error(`An error occurred when fetching API path ${path}`)
+ console.error(err)
+ throw err
+ })
+
+interface Snippet {
+ id: string
+ title: string
+ content: string
+}
+
+interface APISuccess<D> {
+ readonly type: "success"
+ data: D
+}
+
+interface APILoading {
+ readonly type: "loading"
+}
+
+interface APIFailed<E> {
+ readonly type: "failed"
+ error: E
+}
+
+type APIResult<D, E> = APISuccess<D> | APILoading | APIFailed<E>
+
+const mapSWRResult = <D, E>({ data, error }: SWRResponse<D, E>): APIResult<D, E> => {
+ if (error !== undefined) {
+ return { type: "failed", error }
+ }
+
+ const isLoading = data === undefined
+ if (isLoading) {
+ return { type: "loading" }
+ }
+
+ return { type: "success", data }
+}
+
+export const useSnippets = () => mapSWRResult<Snippet[], Error>(
+ useSWR("/snippets", fetcher),
+)