-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathenv.ts
51 lines (40 loc) · 1.7 KB
/
env.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import { createContext } from "npm/react";
import { HttpErrorOptions } from "./error.tsx";
/** For internal use only. */
export const _env = {
isServer: "Deno" in globalThis,
};
/** Used to determine if the code is running on the server. */
export const isServer = () => _env.isServer;
/** Used to determine if the code is running in the browser. */
export const isBrowser = () => !isServer();
export interface AppEnvironment {
[key: string]: string | undefined;
}
export type AppWindow<
AppContext extends Record<string, unknown> = Record<string, unknown>,
> = typeof window & {
app: { env: AppEnvironment; context: AppContext; error?: HttpErrorOptions };
};
/**
* Gets environmental variables.
* In the browser, only environmental variables shared with it by the server will be accessible.
*/
export const getEnv = (
key: string,
) => (isServer() ? Deno.env.get(key) : (window as AppWindow).app.env[key]);
/** Used to determine if the code is running in the test environment. */
export const isTest = () => getEnv("APP_ENV") === "test";
/** Used to determine if the code is running in the development environment. */
export const isDevelopment = () => {
const env = getEnv("APP_ENV");
return !env || env === "development";
};
/** Used to determine if the code is running in the production environment. */
export const isProduction = () => getEnv("APP_ENV") === "production";
/** Creates a context object for the App. State stored within the AppContext will be serialized and shared with the browser. */
export function createAppContext<
AppContext extends Record<string, unknown> = Record<string, unknown>,
>(defaultValue?: AppContext) {
return createContext<AppContext>(defaultValue ?? {} as AppContext);
}