Skip to content

Commit

Permalink
feat: persist default values when skipping validation
Browse files Browse the repository at this point in the history
  • Loading branch information
Bartek532 committed Dec 9, 2024
1 parent e7e2109 commit ac9d586
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 5 deletions.
28 changes: 23 additions & 5 deletions packages/core/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { TypeOf, ZodError, ZodObject, ZodType } from "zod";
import { object } from "zod";
import type { TypeOf, ZodError, ZodObject, ZodType, AnyZodObject } from "zod";
import { object, ZodDefault } from "zod";

export type ErrorMessage<T extends string> = T;
export type Simplify<T> = {
Expand Down Expand Up @@ -212,6 +212,16 @@ export type CreateEnv<
>
>;

const getDefaults = <Schema extends AnyZodObject>(schema: Schema) => {
return Object.fromEntries(
Object.entries(schema.shape).map(([key, value]) => {
if (value instanceof ZodDefault)
return [key, value._def.defaultValue()];
return [key, undefined]
})
)
}

export function createEnv<
TPrefix extends TPrefixFormat,
TServer extends TServerFormat = NonNullable<unknown>,
Expand All @@ -232,9 +242,6 @@ export function createEnv<
}
}

const skip = !!opts.skipValidation;
// biome-ignore lint/suspicious/noExplicitAny: <explanation>
if (skip) return runtimeEnv as any;

const _client = typeof opts.client === "object" ? opts.client : {};
const _server = typeof opts.server === "object" ? opts.server : {};
Expand All @@ -247,6 +254,17 @@ export function createEnv<

const allClient = client.merge(shared);
const allServer = server.merge(shared).merge(client);

const skip = !!opts.skipValidation;
// biome-ignore lint/suspicious/noExplicitAny: <explanation>
if (skip) {
return {
...getDefaults(allServer),
...runtimeEnv,
} as any;
}


const parsed = isServer
? allServer.safeParse(runtimeEnv) // on server we can validate all env vars
: allClient.safeParse(runtimeEnv); // on client we can only validate the ones that are exposed
Expand Down
22 changes: 22 additions & 0 deletions packages/core/test/smoke.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -620,3 +620,25 @@ describe("extending presets", () => {
});
});
});

describe("skipping validation", () => {
test("returns values when present", () => {
const env = createEnv({
server: { BAR: z.string().default("bar") },
runtimeEnv: { BAR: "foo" },
skipValidation: true,
});

expect(env).toMatchObject({ BAR: "foo" });
});

test("returns defaults when values missing", () => {
const env = createEnv({
server: { BAR: z.string().default("bar") },
runtimeEnv: {},
skipValidation: true,
});

expect(env).toMatchObject({ BAR: "bar" });
});
});

0 comments on commit ac9d586

Please sign in to comment.