Last active
April 2, 2022 10:37
-
-
Save Toilal/7467462831f1dd5c82283ddc24a3059b to your computer and use it in GitHub Desktop.
This file contains hidden or 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
import { Module } from '@nestjs/common' | |
import { ConfigModule } from '@nestjs/config' | |
import { CleanEnvironmentModule } from './clean-environment.module' | |
const envFilePath = process.env.NODE_ENV === 'test' ? '.env.test' : undefined | |
@Module({ | |
imports: [ | |
CleanEnvironmentModule.forPredicate(envFilePath, () => process.env.NODE_ENV === 'test'), | |
ConfigModule.forRoot({ | |
expandVariables: true, | |
envFilePath: envFilePath, | |
ignoreEnvVars: process.env.NODE_ENV === 'test' | |
}) | |
] | |
}) | |
export class AppModule { | |
} |
This file contains hidden or 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
import { DynamicModule, Module } from '@nestjs/common' | |
import { parse } from 'dotenv' | |
import fs from 'fs' | |
@Module({}) | |
export class CleanEnvironmentModule { | |
/** | |
* Remove all variables available in .env file from process.env | |
* | |
* @param environmentFilePath | |
* @param predicate | |
*/ | |
static forPredicate (environmentFilePath?: string, predicate?: () => boolean): DynamicModule { | |
if (predicate === undefined || predicate()) { | |
const environmentData = fs.readFileSync(environmentFilePath ?? '.env', { encoding: 'utf8' }) | |
const parsed = new Set(Object.keys(parse(environmentData))) | |
for (const name of Object.keys(process.env)) { | |
if (parsed.has(name)) { | |
delete process.env[name] | |
} | |
} | |
} | |
return { | |
module: CleanEnvironmentModule | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
for those who get error like
readFileSync
is not defined.use this: