Skip to content

docs(validation): add main docs page #3717

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
merged 6 commits into from
Mar 13, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
582 changes: 51 additions & 531 deletions docs/utilities/validation.md

Large diffs are not rendered by default.

30 changes: 30 additions & 0 deletions examples/snippets/validation/advancedBringAjvInstance.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { Logger } from '@aws-lambda-powertools/logger';
import { validate } from '@aws-lambda-powertools/validation';
import { SchemaValidationError } from '@aws-lambda-powertools/validation/errors';
import Ajv2019 from 'ajv/dist/2019';
import { inboundSchema } from './schemas.js';

const logger = new Logger();

const ajv = new Ajv2019();

export const handler = async (event: unknown) => {
try {
await validate({
payload: event,
schema: inboundSchema,
ajv, // (1)!
});

return {
message: 'ok',
};
} catch (error) {
if (error instanceof SchemaValidationError) {
logger.error('Schema validation failed', error);
throw new Error('Invalid event payload');
}

throw error;
}
};
43 changes: 43 additions & 0 deletions examples/snippets/validation/advancedCustomFormats.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { Logger } from '@aws-lambda-powertools/logger';
import { validate } from '@aws-lambda-powertools/validation';
import { SchemaValidationError } from '@aws-lambda-powertools/validation/errors';
import schemaWithCustomFormat from './samples/schemaWithCustomFormat.json';

const logger = new Logger();

const customFormats = {
awsaccountid: /^\d{12}$/,
creditcard: (value: string) => {
// Luhn algorithm (for demonstration purposes only - do not use in production)
const sum = value
.split('')
.reverse()
.reduce((acc, digit, index) => {
const num = Number.parseInt(digit, 10);
return acc + (index % 2 === 0 ? num : num < 5 ? num * 2 : num * 2 - 9);
}, 0);

return sum % 10 === 0;
},
};

export const handler = async (event: unknown) => {
try {
await validate({
payload: event,
schema: schemaWithCustomFormat,
formats: customFormats,
});

return {
message: 'ok',
};
} catch (error) {
if (error instanceof SchemaValidationError) {
logger.error('Schema validation failed', error);
throw new Error('Invalid event payload');
}

throw error;
}
};
25 changes: 25 additions & 0 deletions examples/snippets/validation/advancedExternalRefs.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { validator } from '@aws-lambda-powertools/validation/decorator';
import type { Context } from 'aws-lambda';
import {
type InboundSchema,
defsSchema,
inboundSchema,
outboundSchema,
} from './schemasWithExternalRefs.js';

class Lambda {
@validator({
inboundSchema,
outboundSchema,
externalRefs: [defsSchema],
})
async handler(event: InboundSchema, _context: Context) {
return {
message: `processed ${event.userId}`,
success: true,
};
}
}

const lambda = new Lambda();
export const handler = lambda.handler.bind(lambda);
27 changes: 27 additions & 0 deletions examples/snippets/validation/gettingStartedDecorator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { validator } from '@aws-lambda-powertools/validation/decorator';
import type { Context } from 'aws-lambda';
import {
type InboundSchema,
type OutboundSchema,
inboundSchema,
outboundSchema,
} from './schemas.js';

class Lambda {
@validator({
inboundSchema,
outboundSchema,
})
async handler(
event: InboundSchema,
_context: Context
): Promise<OutboundSchema> {
return {
statusCode: 200,
body: `Hello from ${event.userId}`,
};
}
}

const lambda = new Lambda();
export const handler = lambda.handler.bind(lambda);
19 changes: 19 additions & 0 deletions examples/snippets/validation/gettingStartedEnvelope.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { validator } from '@aws-lambda-powertools/validation/decorator';
import type { Context } from 'aws-lambda';
import { type InboundSchema, inboundSchema } from './schemas.js';

class Lambda {
@validator({
inboundSchema,
envelope: 'detail',
})
async handler(event: InboundSchema, context: Context) {
return {
message: `processed ${event.userId}`,
success: true,
};
}
}

const lambda = new Lambda();
export const handler = lambda.handler.bind(lambda);
20 changes: 20 additions & 0 deletions examples/snippets/validation/gettingStartedEnvelopeBuiltin.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { SQS } from '@aws-lambda-powertools/jmespath/envelopes';
import { Logger } from '@aws-lambda-powertools/logger';
import { validator } from '@aws-lambda-powertools/validation/middleware';
import middy from '@middy/core';
import { type InboundSchema, inboundSchema } from './schemas.js';

const logger = new Logger();

export const handler = middy()
.use(
validator({
inboundSchema,
envelope: SQS,
})
)
.handler(async (event: Array<InboundSchema>) => {
for (const record of event) {
logger.info(`Processing message ${record.userId}`);
}
});
22 changes: 22 additions & 0 deletions examples/snippets/validation/gettingStartedMiddy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { validator } from '@aws-lambda-powertools/validation/middleware';
import middy from '@middy/core';
import {
type InboundSchema,
type OutboundSchema,
inboundSchema,
outboundSchema,
} from './schemas.js';

export const handler = middy()
.use(
validator({
inboundSchema,
outboundSchema,
})
)
.handler(
async (event: InboundSchema): Promise<OutboundSchema> => ({
statusCode: 200,
body: `Hello from ${event.userId}`,
})
);
26 changes: 26 additions & 0 deletions examples/snippets/validation/gettingStartedStandalone.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { Logger } from '@aws-lambda-powertools/logger';
import { validate } from '@aws-lambda-powertools/validation';
import { SchemaValidationError } from '@aws-lambda-powertools/validation/errors';
import { type InboundSchema, inboundSchema } from './schemas.js';

const logger = new Logger();

export const handler = async (event: InboundSchema) => {
try {
validate({
payload: event,
schema: inboundSchema,
});

return {
message: 'ok', // (1)!
};
} catch (error) {
if (error instanceof SchemaValidationError) {
logger.error('Schema validation failed', error);
throw new Error('Invalid event payload');
}

throw error;
}
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{
"version": "0",
"id": "12345678-1234-1234-1234-123456789012",
"detail-type": "myDetailType",
"source": "myEventSource",
"account": "123456789012",
"time": "2017-12-22T18:43:48Z",
"region": "us-west-2",
"resources": [],
"detail": {
"userId": "123"
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
{
"Records": [
{
"messageId": "c80e8021-a70a-42c7-a470-796e1186f753",
"receiptHandle": "AQEBwJnKyrHigUMZj6rYigCgxlaS3SLy0a...",
"body": "{\"userId\":\"123\"}",
"attributes": {
"ApproximateReceiveCount": "3",
"SentTimestamp": "1529104986221",
"SenderId": "AIDAIC6K7FJUZ7Q",
"ApproximateFirstReceiveTimestamp": "1529104986230"
},
"messageAttributes": {},
"md5OfBody": "098f6bcd4621d373cade4e832627b4f6",
"eventSource": "aws:sqs",
"eventSourceARN": "arn:aws:sqs:us-west-2:123456789012:my-queue",
"awsRegion": "us-west-2"
},
{
"messageId": "c80e8021-a70a-42c7-a470-796e1186f753",
"receiptHandle": "AQEBwJnKyrHigUMZj6rYigCgxlaS3SLy0a...",
"body": "{\"userId\":\"456\"}",
"attributes": {
"ApproximateReceiveCount": "3",
"SentTimestamp": "1529104986221",
"SenderId": "AIDAIC6K7FJUZ7Q",
"ApproximateFirstReceiveTimestamp": "1529104986230"
},
"messageAttributes": {},
"md5OfBody": "098f6bcd4621d373cade4e832627b4f6",
"eventSource": "aws:sqs",
"eventSourceARN": "arn:aws:sqs:us-west-2:123456789012:my-queue",
"awsRegion": "us-west-2"
}
]
}
16 changes: 16 additions & 0 deletions examples/snippets/validation/samples/schemaWithCustomFormat.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
{
"type": "object",
"properties": {
"accountId": {
"type": "string",
"format": "awsaccountid"
},
"creditCard": {
"type": "string",
"format": "creditcard"
}
},
"required": [
"accountId"
]
}
38 changes: 38 additions & 0 deletions examples/snippets/validation/schemas.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
const inboundSchema = {
type: 'object',
properties: {
userId: {
type: 'string',
},
},
required: ['userId'],
} as const;

type InboundSchema = {
userId: string;
};

const outboundSchema = {
type: 'object',
properties: {
body: {
type: 'string',
},
statusCode: {
type: 'number',
},
},
required: ['body', 'statusCode'],
} as const;

type OutboundSchema = {
body: string;
statusCode: number;
};

export {
inboundSchema,
outboundSchema,
type InboundSchema,
type OutboundSchema,
};
43 changes: 43 additions & 0 deletions examples/snippets/validation/schemasWithExternalRefs.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
const defsSchema = {
$id: 'http://example.com/schemas/defs.json',
definitions: {
int: { type: 'integer' },
str: { type: 'string' },
},
} as const;

const inboundSchema = {
$id: 'http://example.com/schemas/inbound.json',
type: 'object',
properties: {
userId: { $ref: 'defs.json#/definitions/str' },
},
required: ['userId'],
} as const;

type InboundSchema = {
userId: string;
};

const outboundSchema = {
$id: 'http://example.com/schemas/outbound.json',
type: 'object',
properties: {
body: { $ref: 'defs.json#/definitions/str' },
statusCode: { $ref: 'defs.json#/definitions/int' },
},
required: ['body', 'statusCode'],
} as const;

type OutboundSchema = {
body: string;
statusCode: number;
};

export {
defsSchema,
inboundSchema,
outboundSchema,
type InboundSchema,
type OutboundSchema,
};
1 change: 1 addition & 0 deletions mkdocs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ nav:
- utilities/batch.md
- utilities/jmespath.md
- utilities/parser.md
- utilities/validation.md
- API reference: api"
- Processes:
- Roadmap: roadmap.md
Expand Down
Loading