From 139fde7b986d21a6bfafeea85fc4f597146af944 Mon Sep 17 00:00:00 2001 From: ledouxm Date: Wed, 9 Oct 2024 19:02:59 +0200 Subject: [PATCH] feat: set url in idb so SW can use it --- packages/frontend/src/api.ts | 31 +++++++++++++--------- packages/frontend/src/service-worker/sw.ts | 10 ++++--- 2 files changed, 25 insertions(+), 16 deletions(-) diff --git a/packages/frontend/src/api.ts b/packages/frontend/src/api.ts index 794826ae..5787f6b8 100644 --- a/packages/frontend/src/api.ts +++ b/packages/frontend/src/api.ts @@ -4,29 +4,34 @@ import { ENV } from "./envVars"; import { createStore, get, set } from "idb-keyval"; -export const api = createApiClient((method, url, parameters) => { - const { body, query, header } = parameters || {}; - - return ofetch(url, { - method, - body: body as any, - query, - headers: { ...header, Authorization: ref.token ? `Bearer ${ref.token}` : undefined } as Record, - }); -}, ENV.VITE_BACKEND_URL); +export const apiStore = createStore("auth", "access"); + +export const createApiClientWithUrl = (url: string) => { + return createApiClient((method, url, parameters) => { + const { body, query, header } = parameters || {}; + + return ofetch(url, { + method, + body: body as any, + query, + headers: { ...header, Authorization: ref.token ? `Bearer ${ref.token}` : undefined } as Record, + }); + }, url); +}; +export const api = createApiClientWithUrl(ENV.VITE_BACKEND_URL); +set("url", ENV.VITE_BACKEND_URL, apiStore); const ref = { token: null as string | null, }; export const setToken = (token?: string | null) => { ref.token = token ?? null; - set("token", token, store); + set("token", token, apiStore); }; -const store = createStore("auth", "access"); export const getTokenFromIdb = async () => { - return get("token", store); + return get("token", apiStore); }; export type RouterInputs = AllEndpoints[T]["parameters"]; diff --git a/packages/frontend/src/service-worker/sw.ts b/packages/frontend/src/service-worker/sw.ts index 1b31d398..45462551 100644 --- a/packages/frontend/src/service-worker/sw.ts +++ b/packages/frontend/src/service-worker/sw.ts @@ -1,7 +1,5 @@ -importScripts("/swEnv.js"); -console.log(self.ENV); import { precacheAndRoute } from "workbox-precaching"; -import { api, getTokenFromIdb } from "../api"; +import { apiStore, createApiClientWithUrl, getTokenFromIdb } from "../api"; import { getPicturesStore, getToUploadStore } from "../features/idb"; import { get, keys, del } from "idb-keyval"; @@ -43,6 +41,12 @@ const syncPicturesById = async (ids: string[], token: string) => { const localIds = await keys(store); const missingIds = ids.filter((picId) => localIds.includes(picId)); + const url = await get("url", apiStore); + + if (!url) throw new Error("no backend url in service worker"); + + const api = createApiClientWithUrl(url); + for (const picId of missingIds) { const reportId = await get(picId, toUploadStore);