|
| 1 | +import { ParseOptions, Schema } from '../core.ts' |
| 2 | + |
| 3 | +export namespace $Dict { |
| 4 | + export interface Options<S, T extends S = S> { |
| 5 | + inner: Schema<S, T> |
| 6 | + key?: Schema<string> |
| 7 | + } |
| 8 | +} |
| 9 | + |
| 10 | +export class $Dict<S, T extends S = S> extends Schema<Readonly<Record<string, S>>, Record<string, T>> { |
| 11 | + type = 'dict' |
| 12 | + options: $Dict.Options<S, T> |
| 13 | + |
| 14 | + constructor(inner: Schema<S, T>) { |
| 15 | + super() |
| 16 | + this.options = { inner } |
| 17 | + } |
| 18 | + |
| 19 | + key(value: Schema<string>) { |
| 20 | + this.options.key = value |
| 21 | + return this |
| 22 | + } |
| 23 | + |
| 24 | + format() { |
| 25 | + return `Record<${this.options.key ? this.options.key.format() : 'string'}, ${this.options.inner.format()}>` |
| 26 | + } |
| 27 | + |
| 28 | + validate(value: unknown, options: ParseOptions) { |
| 29 | + if (typeof value !== 'object' || value === null || Array.isArray(value)) { |
| 30 | + return this.failure(value, options.path) |
| 31 | + } |
| 32 | + const values: Record<string, T> = {} |
| 33 | + const issues: Schema.Issue[] = [] |
| 34 | + for (const key in value) { |
| 35 | + if (this.options.key) { |
| 36 | + const keyResult = this.options.key.validate(key, options) |
| 37 | + if (keyResult.issues) { |
| 38 | + issues.push(...keyResult.issues) |
| 39 | + } |
| 40 | + } |
| 41 | + const result = this.options.inner.validate((value as any)[key], { |
| 42 | + ...options, |
| 43 | + path: [...options.path || [], key], |
| 44 | + }) |
| 45 | + if (result.issues) { |
| 46 | + issues.push(...result.issues) |
| 47 | + } else { |
| 48 | + values[key] = result.value |
| 49 | + } |
| 50 | + } |
| 51 | + if (issues.length) return { issues } |
| 52 | + return { value: values } |
| 53 | + } |
| 54 | +} |
0 commit comments