|
| 1 | +// Open for other validation libraries, but I haven't found any that were small enough, |
| 2 | +// strongly typed and maintained. |
| 3 | + |
| 4 | +export interface IValidationError { |
| 5 | + path: PropertyKey[]; |
| 6 | + message: string; |
| 7 | +} |
| 8 | + |
| 9 | +export type ValidationResult<T> = |
| 10 | + | { |
| 11 | + success: true; |
| 12 | + value: T; |
| 13 | + } |
| 14 | + | { |
| 15 | + success: false; |
| 16 | + errors: IValidationError[]; |
| 17 | + }; |
| 18 | + |
| 19 | +export type Validator<T> = (scrutinee: unknown) => ValidationResult<T>; |
| 20 | + |
| 21 | +function success<T>(t: T): ValidationResult<T> { |
| 22 | + return { |
| 23 | + success: true, |
| 24 | + value: t, |
| 25 | + }; |
| 26 | +} |
| 27 | +function failure<T>(errors: IValidationError[]): ValidationResult<T> { |
| 28 | + return { |
| 29 | + success: false, |
| 30 | + errors, |
| 31 | + }; |
| 32 | +} |
| 33 | + |
| 34 | +function typeGuard<T>(name: string, guard: (arg: unknown) => arg is T): Validator<T> { |
| 35 | + return (scrutinee) => { |
| 36 | + if (guard(scrutinee)) { |
| 37 | + return success(scrutinee); |
| 38 | + } |
| 39 | + return failure([ |
| 40 | + { |
| 41 | + path: [], |
| 42 | + message: `expected a ${name}`, |
| 43 | + }, |
| 44 | + ]); |
| 45 | + }; |
| 46 | +} |
| 47 | + |
| 48 | +export function string(): Validator<string> { |
| 49 | + function stringGuard(arg: unknown): arg is string { |
| 50 | + return typeof arg === 'string'; |
| 51 | + } |
| 52 | + return typeGuard('string', stringGuard); |
| 53 | +} |
| 54 | + |
| 55 | +export function boolean(): Validator<boolean> { |
| 56 | + function boolGuard(arg: unknown): arg is boolean { |
| 57 | + return typeof arg === 'boolean'; |
| 58 | + } |
| 59 | + return typeGuard('boolean', boolGuard); |
| 60 | +} |
| 61 | + |
| 62 | +function hasOwnProperty<X extends {}, Y extends PropertyKey>(obj: X, prop: Y): obj is X & Record<Y, unknown> { |
| 63 | + return obj.hasOwnProperty(prop); |
| 64 | +} |
| 65 | + |
| 66 | +export function object<S>(schema: { [P in keyof S]: Validator<S[P]> }): Validator<{ [P in keyof S]: S[P] }> { |
| 67 | + return (scrutinee) => { |
| 68 | + if (typeof scrutinee !== 'object' || scrutinee === null) { |
| 69 | + return failure([ |
| 70 | + { |
| 71 | + path: [], |
| 72 | + message: 'expected an object', |
| 73 | + }, |
| 74 | + ]); |
| 75 | + } |
| 76 | + |
| 77 | + const errors: IValidationError[] = []; |
| 78 | + let validationFailed = false; |
| 79 | + for (const key in schema) { |
| 80 | + if (!schema[key]) { |
| 81 | + continue; |
| 82 | + } |
| 83 | + |
| 84 | + // If the deserialized value doesn't have the key, use `undefined` as a placeholder |
| 85 | + // might get replaced with a default value |
| 86 | + const existingSub = hasOwnProperty(scrutinee, key) ? scrutinee[key] : undefined; |
| 87 | + const subResult = schema[key](existingSub); |
| 88 | + |
| 89 | + if (subResult.success) { |
| 90 | + Object.assign(scrutinee, { [key]: subResult.value }); |
| 91 | + } else { |
| 92 | + subResult.errors.forEach((val) => |
| 93 | + errors.push({ |
| 94 | + path: [key, ...val.path], |
| 95 | + message: val.message, |
| 96 | + }) |
| 97 | + ); |
| 98 | + validationFailed = true; |
| 99 | + } |
| 100 | + } |
| 101 | + |
| 102 | + if (!validationFailed) { |
| 103 | + return { |
| 104 | + success: true, |
| 105 | + // when we get here, all properties in S have been validated and assigned, so |
| 106 | + // this type assertion is okay. |
| 107 | + value: scrutinee as { [P in keyof S]: S[P] }, |
| 108 | + }; |
| 109 | + } |
| 110 | + |
| 111 | + return { |
| 112 | + success: false, |
| 113 | + errors, |
| 114 | + }; |
| 115 | + }; |
| 116 | +} |
| 117 | + |
| 118 | +export function array<S>(memberValidator: Validator<S>): Validator<S[]> { |
| 119 | + return (scrutinee) => { |
| 120 | + if (!(scrutinee instanceof Array)) { |
| 121 | + return { |
| 122 | + success: false, |
| 123 | + errors: [ |
| 124 | + { |
| 125 | + path: [], |
| 126 | + message: 'expected an array', |
| 127 | + }, |
| 128 | + ], |
| 129 | + }; |
| 130 | + } |
| 131 | + |
| 132 | + const errors: IValidationError[] = []; |
| 133 | + let validationFailed = false; |
| 134 | + for (let i = 0; i < scrutinee.length; ++i) { |
| 135 | + const subResult = memberValidator(scrutinee[i]); |
| 136 | + if (subResult.success) { |
| 137 | + scrutinee[i] = subResult.value; |
| 138 | + } else { |
| 139 | + subResult.errors.forEach((val) => |
| 140 | + errors.push({ |
| 141 | + path: [i, ...val.path], |
| 142 | + message: val.message, |
| 143 | + }) |
| 144 | + ); |
| 145 | + validationFailed = true; |
| 146 | + } |
| 147 | + } |
| 148 | + |
| 149 | + if (!validationFailed) { |
| 150 | + return { |
| 151 | + success: true, |
| 152 | + value: scrutinee, |
| 153 | + }; |
| 154 | + } |
| 155 | + |
| 156 | + return { |
| 157 | + success: false, |
| 158 | + errors, |
| 159 | + }; |
| 160 | + }; |
| 161 | +} |
| 162 | + |
| 163 | +export function optional<T>(validator: Validator<T>): Validator<T | null> { |
| 164 | + return (scrutinee) => { |
| 165 | + if (scrutinee === null) { |
| 166 | + return { |
| 167 | + success: true, |
| 168 | + value: null, |
| 169 | + }; |
| 170 | + } |
| 171 | + return validator(scrutinee); |
| 172 | + }; |
| 173 | +} |
| 174 | + |
| 175 | +export class ValidationError extends Error { |
| 176 | + constructor(public errors: IValidationError[], message?: string) { |
| 177 | + super(`validation failure: ${errors.length} errors`); |
| 178 | + } |
| 179 | +} |
| 180 | + |
| 181 | +export function parseAndValidate<T>(text: string, validator: Validator<T>): T { |
| 182 | + const value: unknown = JSON.parse(text); |
| 183 | + const result = validator(value); |
| 184 | + if (result.success) { |
| 185 | + return result.value; |
| 186 | + } |
| 187 | + throw new ValidationError(result.errors); |
| 188 | +} |
0 commit comments