add request id

This commit is contained in:
Nikita Galaiko 2023-02-21 11:23:47 +01:00
parent 51aa80cfd9
commit 0ce6b3221f
No known key found for this signature in database
GPG Key ID: EBAB54E845BA519D
3 changed files with 31 additions and 4 deletions

View File

@ -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",

View File

@ -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

View File

@ -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: {