Skip to content

Commit aec5441

Browse files
committed
Add convenience functions to produce CheckSchemaResult values
1 parent f8ed33e commit aec5441

2 files changed

Lines changed: 33 additions & 7 deletions

File tree

lib/entry-points.js

Lines changed: 8 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

src/json/index.ts

Lines changed: 25 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -86,7 +86,7 @@ export function array<T>(validator: Validator<T>) {
8686
return {
8787
validate,
8888
check: (val: unknown, path: string) => {
89-
const result: CheckSchemaResult = { valid: true, unknownKeys: [] };
89+
const result: CheckSchemaResult = successfulCheckSchema();
9090

9191
if (!isArray(val)) {
9292
result.valid = false;
@@ -123,7 +123,7 @@ export function object<
123123
},
124124
check: (val, path) => {
125125
if (!isObject(val)) {
126-
return { valid: false, unknownKeys: [] };
126+
return invalidCheckSchema();
127127
}
128128
return checkSchema(schema, val, {}, path);
129129
},
@@ -142,7 +142,7 @@ export function optionalOrNull<T>(validator: Validator<T>) {
142142
},
143143
check: (val, path) => {
144144
if (val === undefined || val === null) {
145-
return { valid: true, unknownKeys: [] };
145+
return successfulCheckSchema();
146146
}
147147
return validator.check(val, path);
148148
},
@@ -161,7 +161,7 @@ export function optional<T>(validator: Validator<T>) {
161161
},
162162
check: (val, path) => {
163163
if (val === undefined) {
164-
return { valid: true, unknownKeys: [] };
164+
return successfulCheckSchema();
165165
}
166166
return validator.check(val, path);
167167
},
@@ -214,13 +214,33 @@ export interface CheckSchemaResult {
214214
unknownKeys: string[];
215215
}
216216

217+
/**
218+
* Convenience function to produce a `CheckSchemaResult` where `valid: true`.
219+
*/
220+
function successfulCheckSchema(): CheckSchemaResult {
221+
return {
222+
valid: true,
223+
unknownKeys: [],
224+
};
225+
}
226+
227+
/**
228+
* Convenience function to produce a `CheckSchemaResult` where `valid: false`.
229+
*/
230+
function invalidCheckSchema(): CheckSchemaResult {
231+
return {
232+
valid: false,
233+
unknownKeys: [],
234+
};
235+
}
236+
217237
export function checkSchema<S extends Schema>(
218238
schema: S,
219239
obj: UnvalidatedObject<any>,
220240
options: CheckSchemaOptions = {},
221241
path: string = "",
222242
): CheckSchemaResult {
223-
const result: CheckSchemaResult = { valid: true, unknownKeys: [] };
243+
const result: CheckSchemaResult = successfulCheckSchema();
224244
const inputKeys = new Set(Object.keys(obj));
225245

226246
for (const [key, validator] of Object.entries(schema)) {

0 commit comments

Comments
 (0)