From 8255663005672716d8e46345669c288db3ea6ff6 Mon Sep 17 00:00:00 2001 From: Rachel Lambda Samuelsson Date: Sat, 20 Jul 2024 18:57:27 +0200 Subject: [PATCH] api library --- front/src/api/index.ts | 76 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100644 front/src/api/index.ts diff --git a/front/src/api/index.ts b/front/src/api/index.ts new file mode 100644 index 0000000..c953d32 --- /dev/null +++ b/front/src/api/index.ts @@ -0,0 +1,76 @@ +export interface QueryParams { + [key: string]: (string | number) +} + +export interface APIDef { + [key: string]: ({ + kind: "POST", + query?: QueryParams, + request?: Object, + response: Object, + } | { + kind: "GET", + query?: QueryParams, + response: Object, + }) +} + +type A = { + "/api/blah": { + kind: "GET", + request: { + mjau: number + cat: string + } + response: { + status: number + } + } +} + +export type ValidEndPointForMethod + = T[U] extends { kind: method } ? U : never + +export type QR = { query: Object, request: Object } + +export class API { + base: string; + + constructor(base: string) { + this.base = base; + } + + private dispatch(method : "POST" | "GET", + endpoint : keyof T & string, + req : T[typeof endpoint] & QR): + Promise { + let url : URL = new URL(endpoint, this.base) + let opts : RequestInit = { method } + if (req.query != null) { + const params = new URLSearchParams() + for (const [key, value] of Object.entries(req.query)) { + params.set(key, typeof(value) == "string" ? value : value.toString()) + } + url = new URL(params.toString(), url) + } + if (method == "POST" && req.request != null) { + opts.body = JSON.stringify(req.request) + opts.headers = { "Content-Type": "application/json" } + } + return fetch(url, opts) + } + + get(endpoint : ValidEndPointForMethod, + req: T[typeof endpoint] & QR): + Promise { + return this.dispatch("GET", endpoint, req) + } + + post(endpoint : ValidEndPointForMethod, + req: T[typeof endpoint] & QR): + Promise { + return this.dispatch("POST", endpoint, req) + } +} + +const test = new API("mjau")