Skip to content

Commit

Permalink
feat: add boolean schema
Browse files Browse the repository at this point in the history
  • Loading branch information
ASafaeirad committed Apr 13, 2024
1 parent 2149983 commit b27e787
Show file tree
Hide file tree
Showing 3 changed files with 58 additions and 0 deletions.
40 changes: 40 additions & 0 deletions src/Schema/BooleanSchema.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { BooleanSchema } from './BooleanSchema';

describe('Boolean Schema', () => {
it('should throw error when value is not boolean', () => {
const schema = new BooleanSchema({ coerce: false }).setValue('3000');
schema.key = 'key';

expect(() => schema.validate()).toThrow(
new TypeError(
'Invalid configuration: The "key" expected to be "boolean" but a "string" was provided',
),
);
});

it('should fallback to default', () => {
const schema = new BooleanSchema({
default: true,
coerce: false,
}).setValue();
const schema2 = new BooleanSchema({
default: true,
coerce: false,
}).setValue(undefined);
const schema3 = new BooleanSchema({ default: true }).setValue();
const schema4 = new BooleanSchema({ default: true }).setValue(undefined);

expect(schema.parse()).toBe(true);
expect(schema2.parse()).toBe(true);
expect(schema3.parse()).toBe(true);
expect(schema4.parse()).toBe(true);
});

it('should coercion to boolean', () => {
const schema = new BooleanSchema().setValue('1');
const schema2 = new BooleanSchema().setValue(0);

expect(schema.parse()).toBe(true);
expect(schema2.parse()).toBe(false);
});
});
16 changes: 16 additions & 0 deletions src/Schema/BooleanSchema.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { Schema } from './Schema';
import type { SchemaOptions } from './SchemaOptions';

export class BooleanSchema<TInput = any> extends Schema<TInput, boolean> {
constructor(options: SchemaOptions<boolean> = {}) {
super({
...options,
typeConstructor: n => {
console.log(`${n} to boolean`);

return Boolean(n);
},
type: 'boolean',
});
}
}
2 changes: 2 additions & 0 deletions src/Schema/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
export * from './StringSchema';
export * from './NumberSchema';
export * from './BooleanSchema';
export type { SchemaOptions } from './SchemaOptions';
export type { Schema } from './Schema';

0 comments on commit b27e787

Please sign in to comment.