Skip to content

Commit

Permalink
feat: set url in idb so SW can use it
Browse files Browse the repository at this point in the history
  • Loading branch information
ledouxm committed Oct 9, 2024
1 parent af250f5 commit 139fde7
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 16 deletions.
31 changes: 18 additions & 13 deletions packages/frontend/src/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, string>,
});
}, 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<string, string>,
});
}, 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<T extends keyof AllEndpoints> = AllEndpoints[T]["parameters"];
Expand Down
10 changes: 7 additions & 3 deletions packages/frontend/src/service-worker/sw.ts
Original file line number Diff line number Diff line change
@@ -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";

Expand Down Expand Up @@ -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);

Expand Down

0 comments on commit 139fde7

Please sign in to comment.