Skip to content

Commit

Permalink
make promise check a bit DRYer
Browse files Browse the repository at this point in the history
  • Loading branch information
EskiMojo14 committed Jan 28, 2025
1 parent e8c634b commit e92c15b
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 14 deletions.
13 changes: 7 additions & 6 deletions packages/core/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { StandardSchemaDictionary, StandardSchemaV1 } from "./standard";
import { parseWithDictionary } from "./standard";
import { ensureSynchronous, parseWithDictionary } from "./standard";

export type { StandardSchemaV1, StandardSchemaDictionary };

Expand Down Expand Up @@ -292,12 +292,13 @@ export function createEnv<
..._shared,
};

const parsed = opts.createFinalSchema?.(finalSchemaShape as never, isServer)["~standard"].validate(runtimeEnv)
?? parseWithDictionary(finalSchemaShape, runtimeEnv)
const parsed =
opts
.createFinalSchema?.(finalSchemaShape as never, isServer)
["~standard"].validate(runtimeEnv) ??
parseWithDictionary(finalSchemaShape, runtimeEnv);

if (parsed instanceof Promise) {
throw new Error("Validation must be synchronous");
}
ensureSynchronous(parsed, "Validation must be synchronous");

const onValidationError =
opts.onValidationError ??
Expand Down
24 changes: 16 additions & 8 deletions packages/core/src/standard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,21 +88,29 @@ export namespace StandardSchemaDictionary {
};
}

export function ensureSynchronous<T>(
value: T | Promise<T>,
message: string,
): asserts value is T {
if (value instanceof Promise) {
throw new Error(message);
}
}

export function parseWithDictionary<TDict extends StandardSchemaDictionary>(
dictionary: TDict,
value: Record<string, unknown>,
): StandardSchemaV1.Result<StandardSchemaDictionary.InferOutput<TDict>> {
const result: Record<string, unknown> = {};
const issues: StandardSchemaV1.Issue[] = [];
for (const key in dictionary) {
const schema = dictionary[key];
const prop = value[key];
const propResult = schema["~standard"].validate(prop);
if (propResult instanceof Promise) {
throw new Error(
`Validation must be synchronous, but ${key} returned a Promise.`,
);
}
const propResult = dictionary[key]["~standard"].validate(value[key]);

ensureSynchronous(
propResult,
`Validation must be synchronous, but ${key} returned a Promise.`,
);

if (propResult.issues) {
issues.push(
...propResult.issues.map((issue) => ({
Expand Down

0 comments on commit e92c15b

Please sign in to comment.