Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add BaseValidator.describe #267

Merged
merged 2 commits into from
May 8, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions src/validators/BaseValidator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import type { IConstraint } from '../constraints/base/IConstraint';
import type { BaseError } from '../lib/errors/BaseError';

export abstract class BaseValidator<T> {
public description?: string;
protected parent?: object;
protected constraints: readonly IConstraint<T>[] = [];
protected isValidationEnabled: boolean | (() => boolean) | null = null;
Expand Down Expand Up @@ -69,6 +70,12 @@ export abstract class BaseValidator<T> {
return this.addConstraint(whenConstraint<This, T, Key>(key, options, this as unknown as This));
}

public describe(description: string): this {
const clone = this.clone();
clone.description = description;
return clone;
}

public run(value: unknown): Result<T, BaseError> {
let result = this.handle(value) as Result<T, BaseError>;
if (result.isErr()) return result;
Expand Down
8 changes: 8 additions & 0 deletions tests/validators/base.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,14 @@ import { CombinedError, ExpectedValidationError, Result, s, ValidationError } fr
import { expectClonedValidator, expectError, expectModifiedClonedValidator } from '../common/macros/comparators';

describe('BaseValidator', () => {
describe('description', () => {
test('GIVEN a validator THEN returns the description', () => {
const validator = s.string.describe('The name of the user');

expect(validator.description).toBe('The name of the user');
});
});

describe('is', () => {
test("GIVEN any value THEN it's narrowed to schema type", () => {
const predicate = s.string;
Expand Down