All files / src/common env.ts

100% Statements 13/13
87.5% Branches 7/8
100% Functions 1/1
100% Lines 12/12

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 416x 6x                                 6x         23x 23x 23x 4x 4x         23x 23x     1x 1x      
import { z, ZodDefault, ZodOptional, ZodType, ZodTypeDef } from "zod";
import { isNodeRuntime } from "./runtime";
 
type GetFromEnvType = {
  /** JSON.parse is used by default before passing the env variable to schema.parse */
  <T>(name: string, schema: ZodDefault<ZodType<T>>, parseAsJSON?: boolean): T;
  /** JSON.parse is used by default before passing the env variable to schema.parse */
  <T>(
    name: string,
    schema: ZodOptional<ZodType<T>>,
    parseAsJSON?: boolean
  ): T | undefined;
  /** JSON.parse is NOT used before passing the env variable to schema.parse */
  (name: string): string;
  /** if schema is provided JSON.parse is used before passing the env variable to schema.parse */
  <T>(name: string, schema?: ZodType<T>, parseAsJSON?: boolean): T;
};
 
export const getFromEnv: GetFromEnvType = <T = string>(
  name: string,
  schema?: ZodType<T, ZodTypeDef, T | undefined>,
  parseAsJSON = !!schema
) => {
  const envValue = isNodeRuntime() ? process.env[name] : undefined;
  let envValueParsed: unknown = envValue;
  if (parseAsJSON && envValue) {
    try {
      envValueParsed = JSON.parse(envValue);
    } catch (e) {
      // ignore, if value cannot be parsed as a JSON it will be treated as a string
    }
  }
  try {
    return (schema ?? z.string()).parse(envValueParsed);
  } catch (e) {
    // eslint-disable-next-line no-console -- we cannot use logger here to avoid cyclic dependency between logger and env modules
    console.error(`failed to parse ${name} env variable, value ${envValue}`);
    throw new Error(`failed to parse ${name} env variable`, { cause: e });
  }
};