Skip to content

Commit

Permalink
Merge pull request #1346 from MatthiasKunnen/fix-process-env-undefine…
Browse files Browse the repository at this point in the history
…d-assignment

fix(): prevent unexpected process env stringification
  • Loading branch information
kamilmysliwiec authored Jun 12, 2023
2 parents 0a2ca57 + efdb29e commit 7973ee2
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 2 deletions.
9 changes: 7 additions & 2 deletions lib/config.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -192,13 +192,18 @@ export class ConfigModule {
return config;
}

private static assignVariablesToProcess(config: Record<string, any>) {
private static assignVariablesToProcess(config: Record<string, unknown>) {
if (!isObject(config)) {
return;
}
const keys = Object.keys(config).filter(key => !(key in process.env));
keys.forEach(
key => (process.env[key] = (config as Record<string, any>)[key]),
key => {
const value = config[key];
if (typeof value === 'string') {
process.env[key] = value;
}
},
);
}

Expand Down
33 changes: 33 additions & 0 deletions tests/e2e/optional.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { Test } from '@nestjs/testing';
import { AppModule } from '../src/app.module';
import { ConfigService } from '../../lib';

describe('Optional environment variables', () => {
it('should return undefined for optional variables', async () => {
const module = await Test.createTestingModule({
imports: [AppModule.withValidateFunction(() => ({
optional: undefined,
}))],
}).compile();

const app = module.createNestApplication();
await app.init();

const optional = module.get(ConfigService).get('optional')

expect(optional).toEqual(undefined)
});

it('should not assign complex objects back to process.env', async () => {
const module = await Test.createTestingModule({
imports: [AppModule.withValidateFunction(() => ({
complex: {hello: 'there'},
}))],
}).compile();

const app = module.createNestApplication();
await app.init();

expect(process.env.complex).toEqual(undefined)
});
});

0 comments on commit 7973ee2

Please sign in to comment.