fromEnv (config/env.ts)

airi · packages/server-runtime/src/config/env.ts · typescript · MIT
infra

TypeScript helper to read environment variables with optional validation.

// Source: https://github.com/moeru-ai/airi | License: MIT | Copyright 2024-PRESENT Neko Ayaka
// Provided via justclaw.it.com; keep this notice with the code.
import { env } from 'node:process'

export function fromEnv<T extends string>(envKey: string, envDefault?: T, options?: { validator?: (value: string) => value is T }): T | undefined {
  const value = env[envKey] ?? envDefault
  if (value === undefined) {
    return undefined
  }

  if (options?.validator) {
    if (options.validator(value)) {
      return value
    }
    else {
      return undefined
    }
  }

  return value as T
}

See the full source, get the GitHub permalink, and search for more like it.

Get a free API key