justus 0.5.1 → 0.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/types.ts CHANGED
@@ -52,7 +52,17 @@ export const defaultValidationOptions: Readonly<Required<ValidationOptions>> = {
52
52
  export interface Validator<T = any, I = T> extends Iterable<TupleRestParameter<T, I>> {
53
53
  [Symbol.justusValidator]: this
54
54
 
55
- optional?: boolean
55
+ /**
56
+ * A flag indicating whether the type being validated is _optional_ (the input
57
+ * can be `undefined`) or not (default: `false`).
58
+ */
59
+ optional: boolean
60
+ /**
61
+ * The _default_ replaced by this `Validator` when the input is `undefined`.
62
+ *
63
+ * This is used in conjunction with the `optional` flag.
64
+ */
65
+ defaultValue: T | undefined
56
66
 
57
67
  /** Validate a _value_ and optionally convert it to the required `Type` */
58
68
  validate(value: unknown, options?: ValidationOptions | undefined): T
@@ -73,6 +83,7 @@ export function makeValidatorFactory<
73
83
  >(validator: V, factory: F): F & V {
74
84
  return Object.assign(factory, {
75
85
  optional: validator.optional,
86
+ defaultValue: validator.defaultValue,
76
87
  validate: validator.validate.bind(validator),
77
88
  [Symbol.iterator]: validator[Symbol.iterator].bind(validator),
78
89
  [Symbol.justusValidator]: validator,
@@ -87,7 +98,8 @@ export abstract class AbstractValidator<T, I = T>
87
98
  implements Validator<T, I>, Iterable<TupleRestParameter<T, I>> {
88
99
  [Symbol.justusValidator] = this
89
100
 
90
- optional?: boolean = undefined
101
+ optional: boolean = false
102
+ defaultValue: T | undefined = undefined
91
103
 
92
104
  /** Validate a _value_ and optionally convert it to the required `Type` */
93
105
  abstract validate(value: unknown, options?: ValidationOptions | undefined): T
package/src/utilities.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { assertSchema } from './errors'
1
2
  import { registry } from './registry'
2
3
 
3
4
  import type { Schema, Validation, Validator } from './types'
@@ -6,12 +7,10 @@ import type { Schema, Validation, Validator } from './types'
6
7
  * UTILITY FUNCTIONS *
7
8
  * ========================================================================== */
8
9
 
9
- /**
10
- * Return the `Validator` for the given `Validation`.
11
- *
12
- * When `validation` is `undefined` it will return a `Validator<any>`,
13
- */
10
+ /** Return the `Validator` for the given `Validation` */
14
11
  export function getValidator(validation: Validation): Validator {
12
+ assertSchema(validation !== undefined, 'No validator for undefined validation')
13
+
15
14
  // Null is a constant
16
15
  if (validation === null) return new (registry.get('constant'))(null)
17
16