Skip to content

Commit

Permalink
feat(value): add validator for property value
Browse files Browse the repository at this point in the history
  • Loading branch information
TomokiMiyauci committed May 25, 2023
1 parent 0e6ba5b commit cd994e3
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 0 deletions.
2 changes: 2 additions & 0 deletions combinator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { type Display } from "./types.ts";
import { getCount } from "./iter_utils.ts";
import { bind, interpolate, shouldBe, shouldBeBut } from "./utils.ts";
import { KeyValidator } from "./validators/key.ts";
import { ValueValidator } from "./validators/value.ts";
import { RangeValidator } from "./validators/range.ts";
import { FixedArrayValidator } from "./validators/array/fixed_array.ts";
import { DictionaryValidator } from "./validators/object/dictionary.ts";
Expand Down Expand Up @@ -92,6 +93,7 @@ export const between = /* @__PURE__ */ lazy(

// known
export const key = /* @__PURE__ */ lazy(KeyValidator);
export const value = /* @__PURE__ */ lazy(ValueValidator);

// Array
export const fixedArray = /* @__PURE__ */ lazy(FixedArrayValidator);
Expand Down
1 change: 1 addition & 0 deletions mod.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,4 +56,5 @@ export {
uint8,
unique,
validDate,
value,
} from "./combinator.ts";
33 changes: 33 additions & 0 deletions validators/value.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
// deno-lint-ignore-file ban-types
// Copyright 2023-latest Tomoki Miyauchi. All rights reserved. MIT license.
// This module is browser compatible.

import { isEmpty } from "../deps.ts";
import { curryR, fromPath } from "../utils.ts";
import { map } from "../iter_utils.ts";
import { type ValidationFailure, Validator } from "../types.ts";

export class ValueValidator<In, In_ extends In = In>
implements Validator<{}, Record<string, In_>> {
validator: Validator<In, In_>;

constructor(validator: Validator<In, In_>) {
this.validator = validator;
}

is(input: {}): input is Record<string, In_> {
return isEmpty(this.validate(input));
}

*validate(input: {}): Iterable<ValidationFailure> {
for (const [key, value] of Object.entries(input)) {
const createError = curryR(fromPath, key);

yield* map(this.validator.validate(value as In), createError);
}
}

toString(): string {
return `property value of ${this.validator}`;
}
}

0 comments on commit cd994e3

Please sign in to comment.