-
Notifications
You must be signed in to change notification settings - Fork 156
feat(validation): implement validate function and SchemaValidationErr… #3662
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 7 commits into
aws-powertools:main
from
VatsalGoel3:feature/validation-utils
Feb 27, 2025
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
6046e54
feat(validation): implement validate function and SchemaValidationErr…
VatsalGoel3 ecd3f2b
Merge branch 'main' into feature/validation-utils
VatsalGoel3 47ad480
refactor(validation): Extract types, rename errors.ts, add schema com…
VatsalGoel3 a2dc4d0
feat(corrections)
VatsalGoel3 256dbc4
Merge branch 'main' into feature/validation-utils
VatsalGoel3 82421b0
Apply suggestions from code review
dreamorosi bff312b
Merge branch 'main' into feature/validation-utils
dreamorosi 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,9 @@ | ||
export class SchemaValidationError extends Error { | ||
public errors: unknown; | ||
|
||
constructor(message: string, errors?: unknown) { | ||
super(message); | ||
this.name = 'SchemaValidationError'; | ||
this.errors = errors; | ||
} | ||
} |
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 +1,2 @@ | ||
export const foo = () => true; | ||
export { validate } from './validate'; | ||
dreamorosi marked this conversation as resolved.
Show resolved
Hide resolved
|
||
export { SchemaValidationError } from './errors.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 |
---|---|---|
@@ -0,0 +1,18 @@ | ||
import type Ajv from 'ajv'; | ||
export interface ValidateParams<T = unknown> { | ||
payload: unknown; | ||
schema: object; | ||
envelope?: string; | ||
formats?: Record< | ||
string, | ||
| string | ||
| RegExp | ||
| { | ||
type?: 'string' | 'number'; | ||
validate: (data: string) => boolean; | ||
async?: boolean; | ||
} | ||
>; | ||
externalRefs?: object[]; | ||
ajv?: Ajv; | ||
} |
dreamorosi marked this conversation as resolved.
Show resolved
Hide resolved
|
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,43 @@ | ||
import { search } from '@aws-lambda-powertools/jmespath'; | ||
import Ajv, { type ValidateFunction } from 'ajv'; | ||
import { SchemaValidationError } from './errors.js'; | ||
import type { ValidateParams } from './types.js'; | ||
|
||
export function validate<T = unknown>(params: ValidateParams<T>): T { | ||
const { payload, schema, envelope, formats, externalRefs, ajv } = params; | ||
const ajvInstance = ajv || new Ajv({ allErrors: true }); | ||
|
||
if (formats) { | ||
for (const key of Object.keys(formats)) { | ||
ajvInstance.addFormat(key, formats[key]); | ||
} | ||
} | ||
|
||
if (externalRefs) { | ||
for (const refSchema of externalRefs) { | ||
ajvInstance.addSchema(refSchema); | ||
} | ||
} | ||
|
||
let validateFn: ValidateFunction; | ||
try { | ||
validateFn = ajvInstance.compile(schema); | ||
} catch (error) { | ||
dreamorosi marked this conversation as resolved.
Show resolved
Hide resolved
|
||
throw new SchemaValidationError('Failed to compile schema', error); | ||
} | ||
|
||
const trimmedEnvelope = envelope?.trim(); | ||
const dataToValidate = trimmedEnvelope | ||
? search(trimmedEnvelope, payload as Record<string, unknown>) | ||
: payload; | ||
|
||
const valid = validateFn(dataToValidate); | ||
if (!valid) { | ||
throw new SchemaValidationError( | ||
'Schema validation failed', | ||
validateFn.errors | ||
); | ||
} | ||
|
||
return dataToValidate as T; | ||
} |
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,16 +1,18 @@ | ||
import { beforeEach, describe, expect, it, vi } from 'vitest'; | ||
import { foo } from '../../src/index.js'; | ||
import { SchemaValidationError, validate } from '../../src/index.js'; | ||
|
||
describe('Validation', () => { | ||
describe('Index exports', () => { | ||
beforeEach(() => { | ||
vi.clearAllMocks(); | ||
}); | ||
|
||
it('should return true', () => { | ||
// Act | ||
const result = foo(); | ||
it('should export validate as a function', () => { | ||
// Act & Assess | ||
expect(typeof validate).toBe('function'); | ||
}); | ||
|
||
// Assess | ||
expect(result).toBe(true); | ||
it('should export SchemaValidationError as a function', () => { | ||
// Act & Assess | ||
expect(typeof SchemaValidationError).toBe('function'); | ||
}); | ||
}); |
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,167 @@ | ||
import Ajv from 'ajv'; | ||
import { describe, expect, it } from 'vitest'; | ||
import { SchemaValidationError } from '../../src/errors.js'; | ||
import type { ValidateParams } from '../../src/types.js'; | ||
import { validate } from '../../src/validate.js'; | ||
|
||
describe('validate function', () => { | ||
it('returns validated data when payload is valid', () => { | ||
// Prepare | ||
const payload = { name: 'John', age: 30 }; | ||
const schema = { | ||
type: 'object', | ||
properties: { | ||
name: { type: 'string' }, | ||
age: { type: 'number' }, | ||
}, | ||
required: ['name', 'age'], | ||
additionalProperties: false, | ||
}; | ||
|
||
const params: ValidateParams<typeof payload> = { payload, schema }; | ||
|
||
// Act | ||
const result = validate<typeof payload>(params); | ||
|
||
// Assess | ||
expect(result).toEqual(payload); | ||
}); | ||
|
||
it('throws SchemaValidationError when payload is invalid', () => { | ||
// Prepare | ||
const payload = { name: 'John', age: '30' }; | ||
const schema = { | ||
type: 'object', | ||
properties: { | ||
name: { type: 'string' }, | ||
age: { type: 'number' }, | ||
}, | ||
required: ['name', 'age'], | ||
additionalProperties: false, | ||
}; | ||
|
||
const params: ValidateParams = { payload, schema }; | ||
|
||
// Act & Assess | ||
expect(() => validate(params)).toThrow(SchemaValidationError); | ||
}); | ||
|
||
it('extracts data using envelope when provided', () => { | ||
// Prepare | ||
const payload = { | ||
data: { | ||
user: { name: 'Alice', age: 25 }, | ||
}, | ||
}; | ||
const schema = { | ||
type: 'object', | ||
properties: { | ||
name: { type: 'string' }, | ||
age: { type: 'number' }, | ||
}, | ||
required: ['name', 'age'], | ||
additionalProperties: false, | ||
}; | ||
|
||
const envelope = 'data.user'; | ||
const params: ValidateParams = { payload, schema, envelope }; | ||
|
||
// Act | ||
const result = validate(params); | ||
|
||
// Assess | ||
expect(result).toEqual({ name: 'Alice', age: 25 }); | ||
}); | ||
|
||
it('uses provided ajv instance and custom formats', () => { | ||
// Prepare | ||
const payload = { email: '[email protected]' }; | ||
const schema = { | ||
type: 'object', | ||
properties: { | ||
email: { type: 'string', format: 'custom-email' }, | ||
}, | ||
required: ['email'], | ||
additionalProperties: false, | ||
}; | ||
|
||
const ajvInstance = new Ajv({ allErrors: true }); | ||
const formats = { | ||
'custom-email': { | ||
type: 'string', | ||
validate: (email: string) => email.includes('@'), | ||
}, | ||
}; | ||
|
||
const params: ValidateParams = { | ||
payload, | ||
schema, | ||
ajv: ajvInstance, | ||
formats, | ||
}; | ||
|
||
// Act | ||
const result = validate(params); | ||
|
||
// Assess | ||
expect(result).toEqual(payload); | ||
}); | ||
|
||
it('adds external schemas to ajv instance when provided', () => { | ||
// Prepare | ||
const externalSchema = { | ||
$id: 'http://example.com/schemas/address.json', | ||
type: 'object', | ||
properties: { | ||
street: { type: 'string' }, | ||
city: { type: 'string' }, | ||
}, | ||
required: ['street', 'city'], | ||
additionalProperties: false, | ||
}; | ||
|
||
const schema = { | ||
type: 'object', | ||
properties: { | ||
address: { $ref: 'http://example.com/schemas/address.json' }, | ||
}, | ||
required: ['address'], | ||
additionalProperties: false, | ||
}; | ||
|
||
const payload = { | ||
address: { | ||
street: '123 Main St', | ||
city: 'Metropolis', | ||
}, | ||
}; | ||
|
||
const params: ValidateParams = { | ||
payload, | ||
schema, | ||
externalRefs: [externalSchema], | ||
}; | ||
|
||
// Act | ||
const result = validate(params); | ||
|
||
// Assess | ||
expect(result).toEqual(payload); | ||
}); | ||
|
||
it('throws SchemaValidationError when schema compilation fails', () => { | ||
// Prepare | ||
const payload = { name: 'John' }; | ||
const schema = { | ||
type: 'object', | ||
properties: { | ||
name: { type: 'invalid-type' }, | ||
}, | ||
}; | ||
|
||
const params: ValidateParams = { payload, schema }; | ||
|
||
// Act & Assess | ||
expect(() => validate(params)).toThrow(SchemaValidationError); | ||
}); | ||
}); |
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.