Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

manual loading and parsing of dotenv in watch mode #558 #559

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 26 additions & 1 deletion lib/watch/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
const path = require('path')
const cp = require('child_process')
const chalk = require('chalk')
const { readFileSync, existsSync } = require('fs')
const { arrayToRegExp, logWatchVerbose } = require('./utils')
const { GRACEFUL_SHUT } = require('./constants.js')

Expand Down Expand Up @@ -36,10 +37,34 @@ const watch = function (args, ignoreWatch, verboseWatch) {
})

let readyEmitted = false
const envVarsToProtect = [];

const run = (event) => {
const childEvent = { childEvent: event }
const env = Object.assign({}, process.env, childEvent, require('dotenv').config().parsed)

// in order to not override existing env vars, we have to load and parse
// dotenv without modifying process.env
let dotenvParsed = {};
const dotenvPath = path.resolve(process.cwd(), '.env');
if (existsSync(dotenvPath)) {
dotenvParsed = require('dotenv').parse(readFileSync(dotenvPath, { encoding: 'utf-8' }));
if (event == 'start') {
// analyse which env-vars should not be overwritten
Object.keys(dotenvParsed).forEach(function (key) {
if (Object.prototype.hasOwnProperty.call(process.env, key)) {
// if a env var already exists with a different value
// than in parsed dotenv, it has to be protected
if (process.env[key] != dotenvParsed[key]) {
envVarsToProtect.push(key);
}
}
});
}
for (const envVarToProtect of envVarsToProtect) {
delete dotenvParsed[envVarToProtect];
}
}
const env = Object.assign({}, process.env, dotenvParsed, childEvent);

const _child = cp.fork(forkPath, args, {
env,
Expand Down
32 changes: 32 additions & 0 deletions test/start.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -677,6 +677,38 @@ test('should read env variables from .env file', async (t) => {
await fastify.close()
})

test('should read env variables from .env file and not override existing env vars in watch mode', async (t) => {
process.env.GREETING = 'planet'
const testdir = t.testdir({
'.env': 'GREETING=world',
'plugin.js': await readFile(path.join(__dirname, '../examples/plugin-with-env.js'))
})

const cwd = process.cwd()

process.chdir(testdir)

const port = getPort()
const argv = ['-p', port, '-w', path.join(testdir, 'plugin.js')]
const fastifyEmitter = await requireUncached('../start').start(argv)

t.teardown(() => {
process.chdir(cwd)
})

await once(fastifyEmitter, 'ready')

const r1 = await sget({
method: 'GET',
url: `http://localhost:${port}`
})

t.equal(r1.response.statusCode, 200)
t.same(JSON.parse(r1.body), { hello: 'planet' })

await fastifyEmitter.stop()
})

test('crash on unhandled rejection', t => {
t.plan(1)

Expand Down