From 307a942f78b010fedcf4cbc4e2241bf996ab1b93 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marcus=20P=C3=B6hls?= Date: Tue, 7 May 2024 10:33:16 +0200 Subject: [PATCH] use native node tools to load environment variables --- .../load-environment-variables.ts | 25 +++++++++---------- 1 file changed, 12 insertions(+), 13 deletions(-) diff --git a/packages/core/src/bootstrappers/load-environment-variables.ts b/packages/core/src/bootstrappers/load-environment-variables.ts index 7e85d63f..28da3f5c 100644 --- a/packages/core/src/bootstrappers/load-environment-variables.ts +++ b/packages/core/src/bootstrappers/load-environment-variables.ts @@ -1,8 +1,8 @@ import Path from 'node:path' import Fs from '@supercharge/fs' +import { parseEnv } from 'node:util' import { Str } from '@supercharge/strings' -import Dotenv, { DotenvConfigOptions } from 'dotenv' import { Application, Bootstrapper } from '@supercharge/contracts' import { EnvironmentFileError } from '../errors/environment-file-error.js' @@ -31,8 +31,8 @@ export class LoadEnvironmentVariables implements Bootstrapper { * in case the environment file does not exist, an error will be thrown. */ async loadEnvironment (): Promise { - await this.loadDefaultEnvironmentFile() await this.loadSpecificEnvironmentFile() + await this.loadDefaultEnvironmentFile() } /** @@ -42,23 +42,22 @@ export class LoadEnvironmentVariables implements Bootstrapper { const envPath = this.app.environmentFilePath() if (await Fs.notExists(envPath)) { - throw new Error(`Invalid environment file. Cannot find env file "${envPath}".`) + throw new EnvironmentFileError(`Invalid environment file. Cannot find env file "${envPath}".`) } - await this.loadEnvironmentFile( - this.app.environmentFilePath(), { override: false } - ) + await this.loadEnvironmentFile(envPath) } /** - * Load the given environment `file` content into `process.env`. + * Load the environment file from the given `path` into `process.env`. */ - async loadEnvironmentFile (path: string, options: DotenvConfigOptions): Promise { - const { error } = Dotenv.config({ path, ...options }) + async loadEnvironmentFile (envFilePath: string): Promise { + const content = await Fs.content(envFilePath) + const environmentVariables = parseEnv(content) - if (error) { - throw new EnvironmentFileError(`Failed to load environment file "${path}"`, { cause: error }) - } + Object.entries(environmentVariables).forEach(([key, value]) => { + process.env[key] = value + }) } /** @@ -77,7 +76,7 @@ export class LoadEnvironmentVariables implements Bootstrapper { : this.app.resolveFromBasePath(this.app.environmentPath(), `.env.${env}`) if (await Fs.exists(envFilePath)) { - await this.loadEnvironmentFile(envFilePath, { override: true }) + await this.loadEnvironmentFile(envFilePath) } } }