-
Notifications
You must be signed in to change notification settings - Fork 49
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add abstraction over environment values
- Loading branch information
Showing
3 changed files
with
52 additions
and
34 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,44 @@ | ||
import dotenv from "dotenv"; | ||
import path from "path"; | ||
import { clientRoot } from "./paths.js"; | ||
import { z } from "zod"; | ||
|
||
/** Coerces a string to a boolean value in a case insensitive way. */ | ||
const BooleanStringSchema = z | ||
.string() | ||
.refine(s => s.toLowerCase() === "true" || s.toLowerCase() === "false") | ||
.transform(s => s.toLowerCase() === "true"); | ||
|
||
// Define a required schema for the values we expect along with their defaults | ||
const EnvironmentValuesSchema = z.object({ | ||
HOST: z.string().default("localhost"), | ||
PROXY_SERVER_HTTPS_CONNECTION: BooleanStringSchema.default("false"), | ||
PROXY_SERVER_HTTPS_PORT: z.coerce.number().default(443), | ||
PROXY_SERVER_HTTP_PORT: z.coerce.number().default(80), | ||
LOG_LEVEL: z | ||
.enum(["fatal", "error", "warn", "info", "debug", "trace", "silent"]) | ||
.default("debug"), | ||
LOG_STYLE: z.enum(["cloudwatch", "default"]).default("default"), | ||
}); | ||
|
||
// Load environment variables from .env file. | ||
dotenv.config({ | ||
path: [path.join(clientRoot, ".env.local"), path.join(clientRoot, ".env")], | ||
}); | ||
|
||
// Parse the environment values from the process | ||
const parsedEnvironmentValues = EnvironmentValuesSchema.safeParse(process.env); | ||
|
||
if (!parsedEnvironmentValues.success) { | ||
console.error("Failed to parse environment values"); | ||
const flattenedErrors = parsedEnvironmentValues.error.flatten(); | ||
console.error(flattenedErrors.fieldErrors); | ||
process.exit(1); | ||
} | ||
|
||
console.log("Parsed environment values:", parsedEnvironmentValues.data); | ||
|
||
// Adds all environment values to local object | ||
export const env = { | ||
...parsedEnvironmentValues.data, | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters