Skip to content

Commit

Permalink
fix: don't stop validation when value is undefined
Browse files Browse the repository at this point in the history
Close #10
  • Loading branch information
Julien-R44 committed Jun 28, 2023
1 parent 117af0c commit 8ddf07a
Show file tree
Hide file tree
Showing 4 changed files with 40 additions and 2 deletions.
2 changes: 1 addition & 1 deletion src/validators/builtin/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ export function builtinValidation(env: Record<string, string>, schema: PoppinsSc
// Handle undefined aka optional results
if (typeof res === 'undefined') {
delete process.env[key]
return
continue
}

process.env[key] = res
Expand Down
2 changes: 1 addition & 1 deletion src/validators/zod/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ export async function zodValidation(env: Record<string, string>, schema: ZodSche
// Handle undefined aka optional results
if (typeof result.data === 'undefined') {
delete process.env[key]
return
continue
}

process.env[key] = result.data
Expand Down
19 changes: 19 additions & 0 deletions tests/common.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -191,4 +191,23 @@ test.group('vite-plugin-validate-env', (group) => {
await plugin.config(viteConfig, viteEnvConfig)
assert.equal(process.env.VITE_OPTIONAL, undefined)
})

test('dont stop validation after undefined result', async ({ assert }) => {
assert.plan(2)

const plugin = ValidateEnv({
validator: 'builtin',
schema: {
VITE_OPTIONAL: Schema.number.optional(),
VITE_MY_VAR: Schema.string(),
},
})

await fs.add('.env.development', 'VITE_MY_VAR=hello')
// @ts-ignore
await plugin.config(viteConfig, viteEnvConfig)

assert.equal(process.env.VITE_OPTIONAL, undefined)
assert.equal(process.env.VITE_MY_VAR, 'hello')
})
})
19 changes: 19 additions & 0 deletions tests/zod.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -144,4 +144,23 @@ test.group('Zod validation adaptater', (group) => {
await plugin.config(viteConfig, viteEnvConfig)
assert.equal(process.env.VITE_OPTIONAL_ZOD, undefined)
})

test('dont stop validation after undefined result', async ({ assert }) => {
assert.plan(2)

const plugin = ValidateEnv({
validator: 'zod',
schema: {
VITE_OPTIONAL_ZOD: z.string().max(2).optional(),
VITE_MY_VAR: z.string(),
},
})

await fs.add(ENV_FILENAME, 'VITE_MY_VAR=hello')
// @ts-ignore
await plugin.config(viteConfig, viteEnvConfig)

assert.equal(process.env.VITE_OPTIONAL_ZOD, undefined)
assert.equal(process.env.VITE_MY_VAR, 'hello')
})
})

0 comments on commit 8ddf07a

Please sign in to comment.