-
-
Notifications
You must be signed in to change notification settings - Fork 64
Expand file tree
/
Copy pathscalar.ts
More file actions
39 lines (35 loc) · 1.38 KB
/
scalar.ts
File metadata and controls
39 lines (35 loc) · 1.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import type { ValidationSchemaPluginConfig } from './config.js';
import type { Visitor } from './visitor.js';
/**
* Builds a library-specific scalar schema expression.
*
* All five validation libraries follow the same pattern: check for a custom
* `scalarSchemas` override, fall back to a built-in type map for the resolved
* TypeScript type (string/number/boolean), then apply `defaultScalarTypeSchema`,
* and finally warn and return the library fallback.
*
* The only per-library differences are the strings in `typeMap`, the `fallback`
* value, and whether custom schemas need wrapping (yup appends `.defined()`).
*/
export function buildScalarSchema(
config: ValidationSchemaPluginConfig,
visitor: Visitor,
scalarName: string,
options: {
typeMap: Record<'string' | 'number' | 'boolean', string>
fallback: string
wrapCustom?: (schema: string) => string
},
): string {
if (config.scalarSchemas?.[scalarName]) {
const custom = config.scalarSchemas[scalarName];
return options.wrapCustom ? options.wrapCustom(custom) : custom;
}
const tsType = visitor.getScalarType(scalarName);
if (tsType != null && tsType in options.typeMap)
return options.typeMap[tsType as keyof typeof options.typeMap];
if (config.defaultScalarTypeSchema)
return config.defaultScalarTypeSchema;
console.warn('unhandled scalar name:', scalarName);
return options.fallback;
}