Skip to content

Commit

Permalink
feat(utils): add utility for define validator
Browse files Browse the repository at this point in the history
  • Loading branch information
TomokiMiyauci committed Jun 1, 2023
1 parent 067b328 commit dd966ce
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 2 deletions.
2 changes: 1 addition & 1 deletion mod.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,6 @@ export {
validDate,
value,
} from "./factories.ts";
export { lazy } from "./validators/utils.ts";
export { defineValidator, lazy } from "./validators/utils.ts";
export { type TypeStr, TypeValidator } from "./validators/operators/typeof.ts";
export { type Constructor } from "./deps.ts";
22 changes: 22 additions & 0 deletions validators/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,28 @@ export abstract class BasicValidator<In = unknown, A extends In = In>
abstract validate(input: In): Iterable<ValidationFailure>;
}

/** Create {@link Validator} from {@link Validator.validate}.
*
* @example
* import { defineValidator } from "https://deno.land/x/abstruct@$VERSION/validators/utils.ts";
*
* const StringValidator = defineValidator<unknown, string>(function* (input) {
* const typeOf = typeof input;
* if (typeOf !== "string") {
* yield { message: `should be string, actual ${typeOf}`, instancePath: [] };
* }
* });
*/
export function defineValidator<In, A extends In = In>(
validate: (input: In) => Iterable<ValidationFailure>,
): Validator<In, A> {
class Validator extends BasicValidator<In, A> {
validate = validate;
}

return new Validator();
}

/** Crate validator lazily.
*
* @example
Expand Down
12 changes: 11 additions & 1 deletion validators/utils_test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// Copyright 2023-latest Tomoki Miyauchi. All rights reserved. MIT license.

import { BasicValidator, IsValidator, lazy } from "./utils.ts";
import { BasicValidator, defineValidator, IsValidator, lazy } from "./utils.ts";
import { TypeValidator } from "./operators/typeof.ts";
import { ValidationFailure } from "../types.ts";
import {
Expand Down Expand Up @@ -65,3 +65,13 @@ describe("IsValidator", () => {
assertEquals([...new V().validate("")], []);
});
});

describe("defineValidator", () => {
it("should return validator", () => {
const validate = () => [];
const validator = defineValidator<string, "a" | "b">(validate);

assert(validator.validate === validate);
assert(validator.is(""));
});
});

0 comments on commit dd966ce

Please sign in to comment.