From a96d162f649704df5d9b567158366015cbe3172c Mon Sep 17 00:00:00 2001 From: Jan Tuomi Date: Sat, 5 Feb 2022 16:48:16 +0200 Subject: Get basic stuff working --- src/api.ts | 43 ++++++++++++++++++++++++++++++++++++------- 1 file changed, 36 insertions(+), 7 deletions(-) (limited to 'src/api.ts') diff --git a/src/api.ts b/src/api.ts index 7fd9e64..725f0d8 100644 --- a/src/api.ts +++ b/src/api.ts @@ -10,27 +10,31 @@ const fetcher = (path: string) => fetch(`${API_URL}${path}`) throw err }) -interface Snippet { +interface Example { id: string title: string content: string } -interface APISuccess { +export interface APISuccess { readonly type: "success" data: D } -interface APILoading { +export interface APILoading { readonly type: "loading" } -interface APIFailed { +export interface APIFailed { readonly type: "failed" error: E } -type APIResult = APISuccess | APILoading | APIFailed +export interface APINotYetRequested { + readonly type: "not_yet_requested" +} + +export type APIResult = APISuccess | APILoading | APIFailed | APINotYetRequested const mapSWRResult = ({ data, error }: SWRResponse): APIResult => { if (error !== undefined) { @@ -45,6 +49,31 @@ const mapSWRResult = ({ data, error }: SWRResponse): APIResult return { type: "success", data } } -export const useSnippets = () => mapSWRResult( - useSWR("/snippets", fetcher), +const postRequest = async (path: string, body: any, opts?: any): Promise> => { + const url = `${API_URL}${path}` + const body_ = typeof body === "string" ? body : JSON.stringify(body) + try { + const resp = await fetch(url, { method: "POST", body: body_, headers: { + "Content-Type": "application/json", + }, ...opts }) + + if (resp.status >= 400) { + throw new Error(`${url} responded with ${resp.status}: ${resp.text}`) + } + const data = await resp.json() + return { type: "success", data } + } catch (err: any) { + console.error(`An error occurred when POSTing to API path ${path}`) + console.error(err) + return { type: "failed", error: err } + } +} + +export const useExamples = () => mapSWRResult( + useSWR("/examples", fetcher), +) + +export const submitSource = async (text: string) => postRequest( + "/submit", + text, ) -- cgit v1.3