-
Notifications
You must be signed in to change notification settings - Fork 816
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 standard schema support and associated tests #2588
Draft
GregoireBellon
wants to merge
1
commit into
typestack:develop
Choose a base branch
from
GregoireBellon:feat/add-standard-schema
base: develop
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+248
−1
Draft
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,110 @@ | ||
/** | ||
* The Standard Schema interface. | ||
*/ | ||
export type StandardSchemaV1<Input = unknown, Output = Input> = { | ||
/** | ||
* The Standard Schema properties. | ||
*/ | ||
readonly '~standard': StandardSchemaV1.Props<Input, Output>; | ||
}; | ||
|
||
export declare namespace StandardSchemaV1 { | ||
/** | ||
* The Standard Schema properties interface. | ||
*/ | ||
export interface Props<Input = unknown, Output = Input> { | ||
/** | ||
* The version number of the standard. | ||
*/ | ||
readonly version: 1; | ||
/** | ||
* The vendor name of the schema library. | ||
*/ | ||
readonly vendor: string; | ||
/** | ||
* Validates unknown input values. | ||
*/ | ||
readonly validate: (value: unknown) => Result<Output> | Promise<Result<Output>>; | ||
/** | ||
* Inferred types associated with the schema. | ||
*/ | ||
readonly types?: Types<Input, Output> | undefined; | ||
} | ||
|
||
/** | ||
* The result interface of the validate function. | ||
*/ | ||
export type Result<Output> = SuccessResult<Output> | FailureResult; | ||
|
||
/** | ||
* The result interface if validation succeeds. | ||
*/ | ||
export interface SuccessResult<Output> { | ||
/** | ||
* The typed output value. | ||
*/ | ||
readonly value: Output; | ||
/** | ||
* The non-existent issues. | ||
*/ | ||
readonly issues?: undefined; | ||
} | ||
|
||
/** | ||
* The result interface if validation fails. | ||
*/ | ||
export interface FailureResult { | ||
/** | ||
* The issues of failed validation. | ||
*/ | ||
readonly issues: ReadonlyArray<Issue>; | ||
} | ||
|
||
/** | ||
* The issue interface of the failure output. | ||
*/ | ||
export interface Issue { | ||
/** | ||
* The error message of the issue. | ||
*/ | ||
readonly message: string; | ||
/** | ||
* The path of the issue, if any. | ||
*/ | ||
readonly path?: ReadonlyArray<PropertyKey | PathSegment> | undefined; | ||
} | ||
|
||
/** | ||
* The path segment interface of the issue. | ||
*/ | ||
export interface PathSegment { | ||
/** | ||
* The key representing a path segment. | ||
*/ | ||
readonly key: PropertyKey; | ||
} | ||
|
||
/** | ||
* The Standard Schema types interface. | ||
*/ | ||
export interface Types<Input = unknown, Output = Input> { | ||
/** | ||
* The input type of the schema. | ||
*/ | ||
readonly input: Input; | ||
/** | ||
* The output type of the schema. | ||
*/ | ||
readonly output: Output; | ||
} | ||
|
||
/** | ||
* Infers the input type of a Standard Schema. | ||
*/ | ||
export type InferInput<Schema extends StandardSchemaV1> = NonNullable<Schema['~standard']['types']>['input']; | ||
|
||
/** | ||
* Infers the output type of a Standard Schema. | ||
*/ | ||
export type InferOutput<Schema extends StandardSchemaV1> = NonNullable<Schema['~standard']['types']>['output']; | ||
} |
31 changes: 31 additions & 0 deletions
31
src/standard-schema/ValidationSchemaToStandardSchemaAdapters.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,31 @@ | ||
import { ValidationError } from '../validation/ValidationError'; | ||
import { StandardSchemaV1 } from './StandardSchema'; | ||
|
||
export function validationErrorToIssues(valError: ValidationError): StandardSchemaV1.Issue[] { | ||
const results: StandardSchemaV1.Issue[] = []; | ||
const errorsToConvert: { path: string[]; value: ValidationError }[] = [{ path: [], value: valError }]; | ||
|
||
while (errorsToConvert.length > 0) { | ||
// this is safe, since we check the length of the array before | ||
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion | ||
const error = errorsToConvert.pop()!; | ||
|
||
const newPath = [...error.path, error.value.property]; | ||
|
||
Object.values(error.value.constraints ?? {}).forEach(constraintMessage => | ||
results.push({ | ||
message: constraintMessage, | ||
path: newPath, | ||
}) | ||
); | ||
|
||
error.value.children?.reverse().forEach(childError => | ||
errorsToConvert.push({ | ||
path: newPath, | ||
value: childError, | ||
}) | ||
); | ||
} | ||
|
||
return results; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,83 @@ | ||
import { IsString, IsUrl, IsOptional, ValidateNested, MinLength } from '../../src/decorator/decorators'; | ||
import { StandardSchemaV1 } from '../../src/standard-schema/StandardSchema'; | ||
import { validationErrorToIssues } from '../../src/standard-schema/ValidationSchemaToStandardSchemaAdapters'; | ||
import { Validator } from '../../src/validation/Validator'; | ||
|
||
const validator = new Validator(); | ||
|
||
describe('ValidationErrorToStandardSchemaIssues', () => { | ||
it('Should correctly map the Validation Errors into standard schema issues', async () => { | ||
class NestedClass { | ||
@IsString() | ||
public name: string; | ||
|
||
@IsUrl() | ||
public url: string; | ||
|
||
@IsOptional() | ||
@ValidateNested() | ||
public insideNested: NestedClass; | ||
|
||
constructor(url: string, name: any, insideNested?: NestedClass) { | ||
this.url = url; | ||
this.name = name; | ||
this.insideNested = insideNested; | ||
} | ||
} | ||
|
||
class RootClass { | ||
@IsString() | ||
@MinLength(15) | ||
public title: string; | ||
|
||
@ValidateNested() | ||
public nestedObj: NestedClass; | ||
|
||
@ValidateNested({ each: true }) | ||
public nestedArr: NestedClass[]; | ||
|
||
constructor() { | ||
this.title = 5 as any; | ||
this.nestedObj = new NestedClass('invalid-url', 5, new NestedClass('invalid-url', 5)); | ||
this.nestedArr = [new NestedClass('invalid-url', 5), new NestedClass('invalid-url', 5)]; | ||
} | ||
} | ||
|
||
const validationErrors = await validator.validate(new RootClass()); | ||
const mappedErrors: StandardSchemaV1.Issue[] = []; | ||
|
||
validationErrors.forEach(valError => mappedErrors.push(...validationErrorToIssues(valError))); | ||
|
||
expect(mappedErrors).toHaveLength(10); | ||
|
||
expect(mappedErrors[0].path).toStrictEqual(['title']); | ||
expect(mappedErrors[0].message).toStrictEqual('title must be longer than or equal to 15 characters'); | ||
|
||
expect(mappedErrors[1].path).toStrictEqual(['title']); | ||
expect(mappedErrors[1].message).toStrictEqual('title must be a string'); | ||
|
||
expect(mappedErrors[2].path).toStrictEqual(['nestedObj', 'name']); | ||
expect(mappedErrors[2].message).toStrictEqual('name must be a string'); | ||
|
||
expect(mappedErrors[3].path).toStrictEqual(['nestedObj', 'url']); | ||
expect(mappedErrors[3].message).toStrictEqual('url must be a URL address'); | ||
|
||
expect(mappedErrors[4].path).toStrictEqual(['nestedObj', 'insideNested', 'name']); | ||
expect(mappedErrors[4].message).toStrictEqual('name must be a string'); | ||
|
||
expect(mappedErrors[5].path).toStrictEqual(['nestedObj', 'insideNested', 'url']); | ||
expect(mappedErrors[5].message).toStrictEqual('url must be a URL address'); | ||
|
||
expect(mappedErrors[6].path).toStrictEqual(['nestedArr', '0', 'name']); | ||
expect(mappedErrors[6].message).toStrictEqual('name must be a string'); | ||
|
||
expect(mappedErrors[7].path).toStrictEqual(['nestedArr', '0', 'url']); | ||
expect(mappedErrors[7].message).toStrictEqual('url must be a URL address'); | ||
|
||
expect(mappedErrors[8].path).toStrictEqual(['nestedArr', '1', 'name']); | ||
expect(mappedErrors[8].message).toStrictEqual('name must be a string'); | ||
|
||
expect(mappedErrors[9].path).toStrictEqual(['nestedArr', '1', 'url']); | ||
expect(mappedErrors[9].message).toStrictEqual('url must be a URL address'); | ||
}); | ||
}); |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Is this type correct?