diff --git a/package.json b/package.json index 2621d2b1f..b332b0bd8 100644 --- a/package.json +++ b/package.json @@ -20,6 +20,7 @@ "date-fns": "^2.29.3", "idb-keyval": "^6.2.0", "mm-jsr": "^3.0.2", + "nanoid": "^4.0.1", "seti-icons": "^0.0.4", "svelte-icons": "^2.1.0", "tauri-plugin-log-api": "github:tauri-apps/tauri-plugin-log", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 93984c442..0ff57d68d 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -19,6 +19,7 @@ specifiers: eslint-plugin-unicorn: ^45.0.2 idb-keyval: ^6.2.0 mm-jsr: ^3.0.2 + nanoid: ^4.0.1 postcss: ^8.4.14 postcss-load-config: ^4.0.1 prettier: ^2.8.4 @@ -45,6 +46,7 @@ dependencies: date-fns: 2.29.3 idb-keyval: 6.2.0 mm-jsr: 3.0.2 + nanoid: 4.0.1 seti-icons: 0.0.4 svelte-icons: 2.1.0 tauri-plugin-log-api: github.com/tauri-apps/tauri-plugin-log/921afb3366b14ac43e3d8041a7def4b85d4d7192 @@ -1990,6 +1992,12 @@ packages: hasBin: true dev: true + /nanoid/4.0.1: + resolution: {integrity: sha512-udKGtCCUafD3nQtJg9wBhRP3KMbPglUsgV5JVsXhvyBs/oefqb4sqMEhKBBgqZncYowu58p1prsZQBYvAj/Gww==} + engines: {node: ^14 || ^16 || >=18} + hasBin: true + dev: false + /natural-compare/1.4.0: resolution: {integrity: sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==} dev: true diff --git a/src/lib/api.ts b/src/lib/api.ts index a778cdfd2..dc9f985e7 100644 --- a/src/lib/api.ts +++ b/src/lib/api.ts @@ -1,5 +1,6 @@ import { PUBLIC_API_BASE_URL } from "$env/static/public"; import * as log from "$lib/log"; +import { nanoid } from "nanoid"; const apiUrl = new URL("/api/", new URL(PUBLIC_API_BASE_URL)); @@ -45,11 +46,28 @@ const parseResponseJSON = async (response: Response) => { type FetchMiddleware = (f: typeof fetch) => typeof fetch; -const fetchWithLog: FetchMiddleware = (fetch) => async (url, options) => { +const fetchWith = ( + fetch: typeof window.fetch, + ...middlewares: FetchMiddleware[] +) => middlewares.reduce((f, middleware) => middleware(f), fetch); + +const withRequestId: FetchMiddleware = (fetch) => async (url, options) => { + const requestId = nanoid(); + if (!options) options = {}; + options.headers = { + ...options?.headers, + "X-Request-Id": requestId, + }; + return fetch(url, options); +}; + +const withLog: FetchMiddleware = (fetch) => async (url, options) => { log.info("fetch", url, options); try { - return await fetch(url, options); - } catch (e) { + const resp = await fetch(url, options); + log.info(resp); + return resp; + } catch (e: any) { log.error("fetch", e); throw e; } @@ -60,7 +78,7 @@ export default ( fetch: window.fetch, } ) => { - const fetch = fetchWithLog(realFetch); + const fetch = fetchWith(realFetch, withRequestId, withLog); return { login: { token: {