|
1 |
| -import { Schema, SchemaMetaData } from 'type-level-schema/schema'; |
2 |
| -import { objectKeys, Nominal, AnyFunc, AllRequired, Optional, Unknown, PlainObject } from 'simplytyped'; |
| 1 | +import { objectKeys, Nominal, AnyFunc, AllRequired, Optional, Unknown, PlainObject, Omit } from 'simplytyped'; |
3 | 2 | import * as Ajv from 'ajv';
|
4 | 3 |
|
| 4 | +// Schema definitions |
| 5 | +import { Schema, SchemaMetaData } from 'type-level-schema/schema'; |
| 6 | +import { StringSchema } from 'type-level-schema/defs/string'; |
| 7 | +import { NumberSchema } from 'type-level-schema/defs/number'; |
| 8 | +import { BooleanSchema } from 'type-level-schema/defs/boolean'; |
| 9 | +import { ArraySchema } from 'type-level-schema/defs/array'; |
| 10 | +import { ObjectSchema } from 'type-level-schema/defs/object'; |
| 11 | + |
| 12 | +/** |
| 13 | + * no-doc - Gets the full schema definition for a given type. |
| 14 | + */ |
| 15 | +export type TypeToSchema<T> = |
| 16 | + T extends string ? StringSchema : |
| 17 | + T extends number ? NumberSchema : |
| 18 | + T extends boolean ? BooleanSchema : |
| 19 | + T extends any[] ? ArraySchema : |
| 20 | + T extends object ? ObjectSchema : |
| 21 | + never; |
| 22 | + |
| 23 | +/** |
| 24 | + * no-doc - Gets the optional parts of the schema definition for a given type. |
| 25 | + */ |
| 26 | +export type TypeToSchemaOptions<T> = Omit<TypeToSchema<T>, 'type'>; |
| 27 | + |
5 | 28 | /**
|
6 | 29 | * no-doc - Generates an object type from `[string, Validator]` pairs
|
7 | 30 | * @param O a Validator record
|
@@ -182,6 +205,28 @@ export class Validator<T> {
|
182 | 205 | return this;
|
183 | 206 | }
|
184 | 207 |
|
| 208 | + /** |
| 209 | + * Add additional validations to the generated schema. |
| 210 | + * While most of these validations are not representable at compile time |
| 211 | + * with typescript (`minLength` of a `string` for instance), it can be helpful |
| 212 | + * to have the additional validations when validating runtime types. |
| 213 | + * @param opts JSON schema specific options (for instance: `{ maxLength: 2, minLength: 0 }`) |
| 214 | + * |
| 215 | + * @example |
| 216 | + * ```typescript |
| 217 | + * const validator = v.string().withOptions({ minLength: 1 }); |
| 218 | + * validator.isValid(''); // false |
| 219 | + * validator.isValid('hi'); // true |
| 220 | + * ``` |
| 221 | + */ |
| 222 | + withOptions(opts: TypeToSchemaOptions<T>): this { |
| 223 | + this.schema = { |
| 224 | + ...this.schema, |
| 225 | + ...opts as any, |
| 226 | + }; |
| 227 | + return this; |
| 228 | + } |
| 229 | + |
185 | 230 | /**
|
186 | 231 | * Creates a new validator that is true whenever the data matches `this` _or_ `v`.
|
187 | 232 | * @param other Another validator instance whose type will form a union with `this` encapsulated type.
|
|
0 commit comments