Skip to content

Commit 649e26e

Browse files
committed
make promise check a bit DRYer
1 parent e8c634b commit 649e26e

File tree

2 files changed

+22
-14
lines changed

2 files changed

+22
-14
lines changed

packages/core/src/index.ts

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import type { StandardSchemaDictionary, StandardSchemaV1 } from "./standard";
2-
import { parseWithDictionary } from "./standard";
2+
import { ensureSynchronous, parseWithDictionary } from "./standard";
33

44
export type { StandardSchemaV1, StandardSchemaDictionary };
55

@@ -292,12 +292,13 @@ export function createEnv<
292292
..._shared,
293293
};
294294

295-
const parsed = opts.createFinalSchema?.(finalSchemaShape as never, isServer)["~standard"].validate(runtimeEnv)
296-
?? parseWithDictionary(finalSchemaShape, runtimeEnv)
295+
const parsed =
296+
opts
297+
.createFinalSchema?.(finalSchemaShape as never, isServer)
298+
["~standard"].validate(runtimeEnv) ??
299+
parseWithDictionary(finalSchemaShape, runtimeEnv);
297300

298-
if (parsed instanceof Promise) {
299-
throw new Error("Validation must be synchronous");
300-
}
301+
ensureSynchronous(parsed, "Validation must be synchronous");
301302

302303
const onValidationError =
303304
opts.onValidationError ??

packages/core/src/standard.ts

Lines changed: 15 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -88,21 +88,28 @@ export namespace StandardSchemaDictionary {
8888
};
8989
}
9090

91+
export function ensureSynchronous<T>(
92+
value: T | Promise<T>,
93+
message: string,
94+
): asserts value is T {
95+
if (value instanceof Promise) {
96+
throw new Error(message);
97+
}
98+
}
99+
91100
export function parseWithDictionary<TDict extends StandardSchemaDictionary>(
92101
dictionary: TDict,
93102
value: Record<string, unknown>,
94103
): StandardSchemaV1.Result<StandardSchemaDictionary.InferOutput<TDict>> {
95104
const result: Record<string, unknown> = {};
96105
const issues: StandardSchemaV1.Issue[] = [];
97106
for (const key in dictionary) {
98-
const schema = dictionary[key];
99-
const prop = value[key];
100-
const propResult = schema["~standard"].validate(prop);
101-
if (propResult instanceof Promise) {
102-
throw new Error(
103-
`Validation must be synchronous, but ${key} returned a Promise.`,
104-
);
105-
}
107+
const propResult = dictionary[key]["~standard"].validate(value[key]);
108+
ensureSynchronous(
109+
propResult,
110+
`Validation must be synchronous, but ${key} returned a Promise.`,
111+
);
112+
106113
if (propResult.issues) {
107114
issues.push(
108115
...propResult.issues.map((issue) => ({

0 commit comments

Comments
 (0)