-
Notifications
You must be signed in to change notification settings - Fork 156
feat(validation): Add @validator decorator for JSON Schema validation #3679
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
Merged
dreamorosi
merged 10 commits into
aws-powertools:main
from
VatsalGoel3:feature/validator-decorator
Mar 4, 2025
Merged
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
9af077a
feat(validation): add @validator decorator for JSON Schema validation
VatsalGoel3 4e0ea04
Updated the test suite
VatsalGoel3 4984867
updated test suite
VatsalGoel3 81fff4b
Merge branch 'main' into feature/validator-decorator
VatsalGoel3 a4f1060
refactor(validation): update decorator with improved types and schema…
VatsalGoel3 5f5d470
Merge branch 'feature/validator-decorator' of https://github.com/Vats…
VatsalGoel3 8676b00
Update packages/validation/src/decorator.ts
dreamorosi e93f513
Updated imports and exports
VatsalGoel3 e121fa7
Merge branch 'feature/validator-decorator' of https://github.com/Vats…
VatsalGoel3 89c30fd
Merge branch 'main' into feature/validator-decorator
VatsalGoel3 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 hidden or 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,62 @@ | ||
import { SchemaValidationError } from './errors.js'; | ||
import type { ValidatorOptions } from './types.js'; | ||
import { validate } from './validate.js'; | ||
export function validator(options: ValidatorOptions) { | ||
return ( | ||
_target: unknown, | ||
_propertyKey: string | symbol, | ||
descriptor: PropertyDescriptor | ||
) => { | ||
if (!descriptor.value) { | ||
return descriptor; | ||
} | ||
const { | ||
inboundSchema, | ||
outboundSchema, | ||
envelope, | ||
formats, | ||
externalRefs, | ||
ajv, | ||
} = options; | ||
if (!inboundSchema && !outboundSchema) { | ||
return descriptor; | ||
} | ||
const originalMethod = descriptor.value; | ||
descriptor.value = async function (...args: unknown[]) { | ||
let validatedInput = args[0]; | ||
if (inboundSchema) { | ||
try { | ||
validatedInput = validate({ | ||
payload: validatedInput, | ||
schema: inboundSchema, | ||
envelope: envelope, | ||
formats: formats, | ||
externalRefs: externalRefs, | ||
ajv: ajv, | ||
}); | ||
} catch (error) { | ||
throw new SchemaValidationError('Inbound validation failed', error); | ||
} | ||
} | ||
const result = await originalMethod.apply(this, [ | ||
validatedInput, | ||
...args.slice(1), | ||
]); | ||
if (outboundSchema) { | ||
try { | ||
return validate({ | ||
payload: result, | ||
schema: outboundSchema, | ||
formats: formats, | ||
externalRefs: externalRefs, | ||
ajv: ajv, | ||
}); | ||
} catch (error) { | ||
throw new SchemaValidationError('Outbound Validation failed', error); | ||
} | ||
} | ||
return result; | ||
}; | ||
return descriptor; | ||
}; | ||
} |
This file contains hidden or 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 |
---|---|---|
@@ -1,2 +1,3 @@ | ||
export { validate } from './validate'; | ||
export { validate } from './validate.js'; | ||
export { SchemaValidationError } from './errors.js'; | ||
export { validator } from './decorator.js'; |
This file contains hidden or 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 |
---|---|---|
@@ -1,18 +1,36 @@ | ||
import type Ajv from 'ajv'; | ||
export interface ValidateParams<T = unknown> { | ||
import type { | ||
Ajv, | ||
AnySchema, | ||
AsyncFormatDefinition, | ||
FormatDefinition, | ||
} from 'ajv'; | ||
|
||
type Prettify<T> = { | ||
[K in keyof T]: T[K]; | ||
} & {}; | ||
|
||
type ValidateParams = { | ||
payload: unknown; | ||
schema: object; | ||
schema: AnySchema; | ||
envelope?: string; | ||
formats?: Record< | ||
string, | ||
| string | ||
| RegExp | ||
| { | ||
type?: 'string' | 'number'; | ||
validate: (data: string) => boolean; | ||
async?: boolean; | ||
} | ||
| FormatDefinition<string> | ||
| FormatDefinition<number> | ||
| AsyncFormatDefinition<string> | ||
| AsyncFormatDefinition<number> | ||
>; | ||
externalRefs?: object[]; | ||
ajv?: Ajv; | ||
} | ||
}; | ||
|
||
type ValidatorOptions = Prettify< | ||
Omit<ValidateParams, 'payload' | 'schema'> & { | ||
inboundSchema?: AnySchema; | ||
outboundSchema?: AnySchema; | ||
} | ||
>; | ||
|
||
export type { ValidateParams, ValidatorOptions }; |
This file contains hidden or 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 hidden or 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,134 @@ | ||
import { describe, expect, it } from 'vitest'; | ||
import { validator } from '../../src/decorator.js'; | ||
import { SchemaValidationError } from '../../src/errors.js'; | ||
|
||
const inboundSchema = { | ||
type: 'object', | ||
properties: { | ||
value: { type: 'number' }, | ||
}, | ||
required: ['value'], | ||
additionalProperties: false, | ||
}; | ||
|
||
const outboundSchema = { | ||
type: 'object', | ||
properties: { | ||
result: { type: 'number' }, | ||
}, | ||
required: ['result'], | ||
additionalProperties: false, | ||
}; | ||
|
||
describe('validator decorator', () => { | ||
it('should validate inbound and outbound successfully', async () => { | ||
// Prepare | ||
class TestClass { | ||
@validator({ inboundSchema, outboundSchema }) | ||
async multiply(input: { value: number }): Promise<{ result: number }> { | ||
return { result: input.value * 2 }; | ||
} | ||
} | ||
const instance = new TestClass(); | ||
const input = { value: 5 }; | ||
// Act | ||
const output = await instance.multiply(input); | ||
// Assess | ||
expect(output).toEqual({ result: 10 }); | ||
}); | ||
|
||
it('should throw error on inbound validation failure', async () => { | ||
// Prepare | ||
class TestClass { | ||
@validator({ inboundSchema, outboundSchema }) | ||
async multiply(input: { value: number }): Promise<{ result: number }> { | ||
return { result: input.value * 2 }; | ||
} | ||
} | ||
const instance = new TestClass(); | ||
const invalidInput = { value: 'not a number' } as unknown as { | ||
value: number; | ||
}; | ||
// Act & Assess | ||
await expect(instance.multiply(invalidInput)).rejects.toThrow( | ||
SchemaValidationError | ||
); | ||
}); | ||
|
||
it('should throw error on outbound validation failure', async () => { | ||
// Prepare | ||
class TestClassInvalid { | ||
@validator({ inboundSchema, outboundSchema }) | ||
async multiply(input: { value: number }): Promise<{ result: number }> { | ||
return { result: 'invalid' } as unknown as { result: number }; | ||
} | ||
} | ||
const instance = new TestClassInvalid(); | ||
const input = { value: 5 }; | ||
// Act & Assess | ||
await expect(instance.multiply(input)).rejects.toThrow( | ||
SchemaValidationError | ||
); | ||
}); | ||
|
||
it('should no-op when no schemas are provided', async () => { | ||
// Prepare | ||
class TestClassNoOp { | ||
@validator({}) | ||
async echo(input: unknown): Promise<unknown> { | ||
return input; | ||
} | ||
} | ||
const instance = new TestClassNoOp(); | ||
const data = { foo: 'bar' }; | ||
// Act | ||
const result = await instance.echo(data); | ||
// Assess | ||
expect(result).toEqual(data); | ||
}); | ||
|
||
it('should return descriptor unmodified if descriptor.value is undefined', () => { | ||
// Prepare | ||
const descriptor: PropertyDescriptor = {}; | ||
// Act | ||
const result = validator({ inboundSchema })( | ||
null as unknown as object, | ||
'testMethod', | ||
descriptor | ||
); | ||
// Assess | ||
expect(result).toEqual(descriptor); | ||
}); | ||
|
||
it('should validate inbound only', async () => { | ||
// Prepare | ||
class TestClassInbound { | ||
@validator({ inboundSchema }) | ||
async process(input: { value: number }): Promise<{ data: string }> { | ||
return { data: JSON.stringify(input) }; | ||
} | ||
} | ||
const instance = new TestClassInbound(); | ||
const input = { value: 10 }; | ||
// Act | ||
const output = await instance.process(input); | ||
// Assess | ||
expect(output).toEqual({ data: JSON.stringify(input) }); | ||
}); | ||
|
||
it('should validate outbound only', async () => { | ||
// Prepare | ||
class TestClassOutbound { | ||
@validator({ outboundSchema }) | ||
async process(input: { text: string }): Promise<{ result: number }> { | ||
return { result: 42 }; | ||
} | ||
} | ||
const instance = new TestClassOutbound(); | ||
const input = { text: 'hello' }; | ||
// Act | ||
const output = await instance.process(input); | ||
// Assess | ||
expect(output).toEqual({ result: 42 }); | ||
}); | ||
}); |
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.
Uh oh!
There was an error while loading. Please reload this page.