Skip to content

Commit

Permalink
fix: safe parse env
Browse files Browse the repository at this point in the history
  • Loading branch information
ledouxm committed Oct 9, 2024
1 parent fc9772c commit c4ae88d
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 18 deletions.
27 changes: 10 additions & 17 deletions packages/frontend/src/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,23 +7,16 @@ import { createStore, get, set } from "idb-keyval";
export const apiStore = createStore("auth", "access");

export const createApiClientWithUrl = (url: string) => {
try {
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>,
});
}, url);

return api;
} catch (e) {
console.error("error creating api client", e);
return null;
}
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);
Expand Down
12 changes: 11 additions & 1 deletion packages/frontend/src/envVars.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,17 @@ const envSchema = z.object({
const isSW = typeof window === "undefined";
console.log("isSW", isSW);
console.log("isDev", isDev);
export const ENV = envSchema.parse(isDev ? import.meta.env : isSW ? self.ENV : window.ENV);

const safeParseEnv = (env: Record<string, string>) => {
try {
return envSchema.parse(env);
} catch (e) {
console.error("Error parsing env", e);
return {};
}
};

export const ENV = safeParseEnv(isDev ? import.meta.env : isSW ? self.ENV : window.ENV);

declare global {
interface Window {
Expand Down

0 comments on commit c4ae88d

Please sign in to comment.