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

Add Schema Reflection API #211

Merged
merged 19 commits into from
Nov 19, 2023
Merged
Show file tree
Hide file tree
Changes from 12 commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
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
16 changes: 16 additions & 0 deletions library/src/schemas/any/any.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { describe, expect, test } from 'vitest';
import { parse } from '../../methods/index.ts';
import { toCustom } from '../../transformations/index.ts';
import { maxLength } from '../../validations/index.ts';
import { any } from './any.ts';

describe('any', () => {
Expand All @@ -22,4 +23,19 @@ describe('any', () => {
const output = parse(any([toCustom(transformInput)]), 123);
expect(output).toBe(transformInput());
});

test(`should expose a pipe of transforms and validations`, () => {
const schema1 = any([toCustom(String), maxLength(5)]);
expect(schema1.pipe).toStrictEqual([
expect.objectContaining({ kind: 'to_custom' }),
expect.objectContaining({
kind: 'max_length',
requirement: 5,
message: 'Invalid length',
}),
]);

const schema2 = any();
expect(schema2.pipe).toStrictEqual([]);
});
});
24 changes: 7 additions & 17 deletions library/src/schemas/any/any.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,11 @@ import { executePipe } from '../../utils/index.ts';
* Any schema type.
*/
export type AnySchema<TOutput = any> = BaseSchema<any, TOutput> & {
schema: 'any';
kind: 'any';
/**
* Validation and transformation pipe.
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For types, I don't think these inline comments are necessary.

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As a result of your comment, I have changed my mind on this. Thank you for this improvement. However, I would prefer to add a blank line before a comment that starts with /** for a better overview.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'll make a pass over everything tonight to try and clean up the formatting.

*/
pipe: Pipe<any>;
};

/**
Expand All @@ -17,24 +21,10 @@ export type AnySchema<TOutput = any> = BaseSchema<any, TOutput> & {
*/
export function any(pipe: Pipe<any> = []): AnySchema {
return {
/**
* The schema type.
*/
schema: 'any',

/**
* Whether it's async.
*/
kind: 'any',
async: false,
pipe,

/**
fabian-hiller marked this conversation as resolved.
Show resolved Hide resolved
* Parses unknown input based on its schema.
*
* @param input The input to be parsed.
* @param info The parse info.
*
* @returns The parsed output.
*/
_parse(input, info) {
return executePipe(input, pipe, info, 'any');
},
Expand Down
16 changes: 16 additions & 0 deletions library/src/schemas/any/anyAsync.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { describe, expect, test } from 'vitest';
import { parseAsync } from '../../methods/index.ts';
import { toCustom } from '../../transformations/index.ts';
import { maxLength } from '../../validations/index.ts';
import { anyAsync } from './anyAsync.ts';

describe('anyAsync', () => {
Expand All @@ -22,4 +23,19 @@ describe('anyAsync', () => {
const output = await parseAsync(anyAsync([toCustom(transformInput)]), 123);
expect(output).toBe(transformInput());
});

test(`should expose a pipe of transforms and validations`, () => {
const schema1 = anyAsync([toCustom(String), maxLength(5)]);
expect(schema1.pipe).toStrictEqual([
expect.objectContaining({ kind: 'to_custom' }),
expect.objectContaining({
kind: 'max_length',
requirement: 5,
message: 'Invalid length',
}),
]);

const schema2 = anyAsync();
expect(schema2.pipe).toStrictEqual([]);
});
});
25 changes: 7 additions & 18 deletions library/src/schemas/any/anyAsync.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,11 @@ import { executePipeAsync } from '../../utils/index.ts';
* Any schema type.
*/
export type AnySchemaAsync<TOutput = any> = BaseSchemaAsync<any, TOutput> & {
schema: 'any';
kind: 'any';
/**
* Validation and transformation pipe.
*/
pipe: PipeAsync<any>;
};

/**
Expand All @@ -17,24 +21,9 @@ export type AnySchemaAsync<TOutput = any> = BaseSchemaAsync<any, TOutput> & {
*/
export function anyAsync(pipe: PipeAsync<any> = []): AnySchemaAsync {
return {
/**
* The schema type.
*/
schema: 'any',

/**
* Whether it's async.
*/
kind: 'any',
async: true,

/**
* Parses unknown input based on its schema.
*
* @param input The input to be parsed.
* @param info The parse info.
*
* @returns The parsed output.
*/
pipe,
async _parse(input, info) {
return executePipeAsync(input, pipe, info, 'any');
},
Expand Down
14 changes: 14 additions & 0 deletions library/src/schemas/array/array.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,4 +112,18 @@ describe('array', () => {
expect(() => parse(schema2, [1, 2])).toThrowError(lengthError);
expect(() => parse(schema2, [1])).toThrowError(contentError);
});

test(`should expose a pipe of transforms and validations`, () => {
const schema1 = array(string(), [maxLength(5)]);
expect(schema1.pipe).toStrictEqual([
expect.objectContaining({
kind: 'max_length',
requirement: 5,
message: 'Invalid length',
}),
]);

const schema2 = array(string());
expect(schema2.pipe).toStrictEqual([]);
});
});
37 changes: 13 additions & 24 deletions library/src/schemas/array/array.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,16 @@ export type ArraySchema<
TArrayItem extends BaseSchema,
TOutput = Output<TArrayItem>[]
> = BaseSchema<Input<TArrayItem>[], TOutput> & {
schema: 'array';
kind: 'array';
/**
* The array item schema.
*/
array: { item: TArrayItem };
/**
* Validation checks that will be run against
* the input value.
*/
pipe: Pipe<Output<TArrayItem>[]>;
};

/**
Expand Down Expand Up @@ -59,33 +67,14 @@ export function array<TArrayItem extends BaseSchema>(
arg3?: Pipe<Output<TArrayItem>[]>
): ArraySchema<TArrayItem> {
// Get error and pipe argument
const [error, pipe] = getDefaultArgs(arg2, arg3);
const [error, pipe = []] = getDefaultArgs(arg2, arg3);

// Create and return array schema
return {
/**
* The schema type.
*/
schema: 'array',

/**
* The array item schema.
*/
array: { item },

/**
* Whether it's async.
*/
kind: 'array',
async: false,

/**
* Parses unknown input based on its schema.
*
* @param input The input to be parsed.
* @param info The parse info.
*
* @returns The parsed output.
*/
array: { item },
pipe,
_parse(input, info) {
// Check type of input
if (!Array.isArray(input)) {
Expand Down
14 changes: 14 additions & 0 deletions library/src/schemas/array/arrayAsync.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -114,4 +114,18 @@ describe('array', () => {
await expect(parseAsync(schema2, [1, 2])).rejects.toThrowError(lengthError);
await expect(parseAsync(schema2, [1])).rejects.toThrowError(contentError);
});

test(`should expose a pipe of transforms and validations`, () => {
const schema1 = arrayAsync(string(), [maxLength(5)]);
expect(schema1.pipe).toStrictEqual([
expect.objectContaining({
kind: 'max_length',
requirement: 5,
message: 'Invalid length',
}),
]);

const schema2 = arrayAsync(string());
expect(schema2.pipe).toStrictEqual([]);
});
});
37 changes: 13 additions & 24 deletions library/src/schemas/array/arrayAsync.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,16 @@ export type ArraySchemaAsync<
TArrayItem extends BaseSchema | BaseSchemaAsync,
TOutput = Output<TArrayItem>[]
> = BaseSchemaAsync<Input<TArrayItem>[], TOutput> & {
schema: 'array';
kind: 'array';
/**
* The array item schema.
*/
array: { item: TArrayItem };
/**
* Validation checks that will be run against
* the input value.
*/
pipe: PipeAsync<Output<TArrayItem>[]>;
};

/**
Expand Down Expand Up @@ -60,33 +68,14 @@ export function arrayAsync<TArrayItem extends BaseSchema | BaseSchemaAsync>(
arg3?: PipeAsync<Output<TArrayItem>[]>
): ArraySchemaAsync<TArrayItem> {
// Get error and pipe argument
const [error, pipe] = getDefaultArgs(arg2, arg3);
const [error, pipe = []] = getDefaultArgs(arg2, arg3);

// Create and return async array schema
return {
/**
* The schema type.
*/
schema: 'array',

/**
* The array item schema.
*/
array: { item },

/**
* Whether it's async.
*/
kind: 'array',
async: true,

/**
* Parses unknown input based on its schema.
*
* @param input The input to be parsed.
* @param info The parse info.
*
* @returns The parsed output.
*/
array: { item },
pipe,
async _parse(input, info) {
// Check type of input
if (!Array.isArray(input)) {
Expand Down
14 changes: 14 additions & 0 deletions library/src/schemas/bigint/bigint.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,4 +35,18 @@ describe('bigint', () => {
expect(output2).toEqual(input2);
expect(() => parse(schema2, 12346789n)).toThrowError(valueError);
});

test(`should expose a pipe of transforms and validations`, () => {
const schema1 = bigint([maxValue(500n)]);
expect(schema1.pipe).toStrictEqual([
expect.objectContaining({
kind: 'max_value',
requirement: 500n,
message: 'Invalid value',
}),
]);

const schema2 = bigint();
expect(schema2.pipe).toStrictEqual([]);
});
});
27 changes: 8 additions & 19 deletions library/src/schemas/bigint/bigint.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,11 @@ import {
* Bigint schema type.
*/
export type BigintSchema<TOutput = bigint> = BaseSchema<bigint, TOutput> & {
schema: 'bigint';
kind: 'bigint';
/**
* Validation and transformation pipe.
*/
pipe: Pipe<bigint>;
};

/**
Expand All @@ -36,28 +40,13 @@ export function bigint(
arg2?: Pipe<bigint>
): BigintSchema {
// Get error and pipe argument
const [error, pipe] = getDefaultArgs(arg1, arg2);
const [error, pipe = []] = getDefaultArgs(arg1, arg2);

// Create and return bigint schema
return {
/**
* The schema type.
*/
schema: 'bigint',

/**
* Whether it's async.
*/
kind: 'bigint',
Copy link
Owner

@fabian-hiller fabian-hiller Oct 20, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would you prefer kind over type? If so, for what reason?

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If think that type is more generic and also reduces the bundle size a bit. However, the bundle size is negligible here. I am mainly interested in good naming.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think kind would be better so that it doesn't have a potential conflict if someone is trying to build out a JSON schema library on top of this.

It's also what I've seen commonly used to differentiate similar types in discriminated unions, which is basically what we have here to refer to all schemas/validations/transforms that extend a common base class.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If anything, this would be better read as type: "schema", kind: "bigint" for example. Where type refers to the base type we're extending from, and kind refers to the sub-type.

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I understand the JSON argument, but would not consider it for Valibot as it seems too irrelevant at the moment. I think kind is fine and am happy with either name. I just thought type was more commonly used for differentiation. We can continue with kind and update if needed before v1 if we have better ideas or arguments.

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If anything, this would be better read as type: "schema", kind: "bigint" for example. Where type refers to the base type we're extending from, and kind refers to the sub-type.

That's a good argument!

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have been reading about the difference between kind and type. Several sources have indicated that kind refers to a group with certain attributes, while type refers to a specific item. So I prefer to continue with type.

async: false,

/**
* Parses unknown input based on its schema.
*
* @param input The input to be parsed.
* @param info The parse info.
*
* @returns The parsed output.
*/
pipe,
_parse(input, info) {
// Check type of input
if (typeof input !== 'bigint') {
Expand Down
14 changes: 14 additions & 0 deletions library/src/schemas/bigint/bigintAsync.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,4 +39,18 @@ describe('bigintAsync', () => {
valueError
);
});

test(`should expose a pipe of transforms and validations`, () => {
const schema1 = bigintAsync([maxValue(500n)]);
expect(schema1.pipe).toStrictEqual([
expect.objectContaining({
kind: 'max_value',
requirement: 500n,
message: 'Invalid value',
}),
]);

const schema2 = bigintAsync();
expect(schema2.pipe).toStrictEqual([]);
});
});
Loading