Skip to content

Commit d2978df

Browse files
committed
feat(object): add validator for object
1 parent 548e6ee commit d2978df

1 file changed

Lines changed: 32 additions & 0 deletions

File tree

validators/object.ts

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
// Copyright 2023-latest Tomoki Miyauchi. All rights reserved. MIT license.
2+
// This module is browser compatible.
3+
4+
import { map } from "../iter_utils.ts";
5+
import { fromPath, partialR } from "../utils.ts";
6+
import {
7+
Assert,
8+
AssertiveValidator,
9+
Validation,
10+
ValidationError,
11+
} from "../types.ts";
12+
13+
export class ObjectValidator<
14+
const In extends Record<string, unknown>,
15+
const In_ extends In = In,
16+
> implements AssertiveValidator<In, In_> {
17+
declare [Assert.symbol]: In_;
18+
constructor(
19+
public validators:
20+
& { [k in keyof In]: Validation<In[k], In_[k]> }
21+
& { [k in keyof In_]: Validation<In_[k]> },
22+
) {}
23+
24+
*validate(input: In): Iterable<ValidationError> {
25+
for (const [key, validator] of Object.entries(this.validators)) {
26+
const value = input[key];
27+
const iterable = validator.validate(value as never);
28+
29+
yield* map(iterable, partialR(fromPath, key));
30+
}
31+
}
32+
}

0 commit comments

Comments
 (0)