Skip to content

Commit

Permalink
fix: respect existing variables
Browse files Browse the repository at this point in the history
  • Loading branch information
test123456789012345 committed Mar 24, 2020
1 parent 92d1b0f commit 7d5c49e
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 14 deletions.
35 changes: 21 additions & 14 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import findUp from 'find-up'
import safeRequire from 'safe-require'
import { constantCase } from 'constant-case'
import { forIn, keys } from '@dword-design/functions'
import { keys, zipObject, map, identity, pickBy, mapValues, mapKeys } from '@dword-design/functions'
import Ajv from 'ajv'

const ajv = new Ajv({ useDefaults: true })
Expand All @@ -11,12 +11,21 @@ export default {
const envPath = findUp.sync('.env.json')
const schemaPath = findUp.sync('.env.schema.json')

const env = envPath !== undefined ? safeRequire(envPath) : {}
const loadedSchema = schemaPath !== undefined ? safeRequire(schemaPath) : {}
const properties = schemaPath !== undefined ? safeRequire(schemaPath) : {}
const propertyNames = properties |> keys
const env = {
...envPath !== undefined ? safeRequire(envPath) : {},
...zipObject(
propertyNames,
propertyNames |> map(propertyName => process.env[propertyName |> constantCase]),
)
|> pickBy(identity),
}

const schema = {
type: 'object',
properties: loadedSchema,
required: loadedSchema |> keys,
properties,
required: propertyNames,
additionalProperties: false,
}

Expand All @@ -26,14 +35,12 @@ export default {
throw new Error(`dotenv: ${ajv.errorsText()}`)
}
}
env
|> forIn((value, key) => {
const envKey = key |> constantCase
if (process.env[envKey] === undefined) {
process.env[envKey] = typeof value === 'object'
? JSON.stringify(value)
: value
}
})

Object.assign(
process.env,
env
|> mapValues(value => typeof value === 'object' ? (value |> JSON.stringify) : value)
|> mapKeys((value, key) => key |> constantCase),
)
},
}
13 changes: 13 additions & 0 deletions src/index.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,19 @@ export default {
dotenv.config()
expect(process.env.FOO).toEqual('bar')
}),
'other existing variable': () => withLocalTmpDir(async () => {
process.env.FOO = 'bar'
process.env.BAR = 'bar'
await outputFile('.env.schema.json', { foo: { type: 'string' } } |> JSON.stringify)
dotenv.config()
expect(process.env.FOO).toEqual('bar')
}),
'existing variable without .env.json': () => withLocalTmpDir(async () => {
process.env.FOO = 'bar'
await outputFile('.env.schema.json', { foo: { type: 'string' } } |> JSON.stringify)
dotenv.config()
expect(process.env.FOO).toEqual('bar')
}),
empty: () => withLocalTmpDir(() => dotenv.config()),
valid: () => withLocalTmpDir(async () => {
delete process.env.FOO
Expand Down

0 comments on commit 7d5c49e

Please sign in to comment.