Skip to content

Commit 4f526ec

Browse files
dreamorosiAlexander Melnykam29derikayao93antstanley
authored
docs(parser): add utility readme (aws-powertools#2360)
* init parser package * add init config * feat(logger): Support for external observability providers (aws-powertools#1511) * Updated formatAttributes for additional parameters and LogItem return type * Updated the unit tests to pass with new formatter * Updated Powertool named objects to Powertools * Updated tests to match new naming consistency * Updated for tests for new naming consistency * Updated formatter for new design decisions * Update Logger for ephemeral attributes * Update bringYourOwnFormatter documentation to match new formatter --------- Co-authored-by: erikayao93 <[email protected]> * chore(logger): PowertoolsLogFormatter docstring and variable naming update (aws-powertools#1585) * Updated formatAttributes for additional parameters and LogItem return type * Updated the unit tests to pass with new formatter * Updated Powertool named objects to Powertools * Updated tests to match new naming consistency * Updated for tests for new naming consistency * Updated formatter for new design decisions * Update Logger for ephemeral attributes * Update bringYourOwnFormatter documentation to match new formatter * Fixed incorrect return type, renamed variable for consistency * feat(logger): Support for external observability providers (aws-powertools#1511) * Updated formatAttributes for additional parameters and LogItem return type * Updated the unit tests to pass with new formatter * Updated Powertool named objects to Powertools * Updated tests to match new naming consistency * Updated for tests for new naming consistency * Updated formatter for new design decisions * Update Logger for ephemeral attributes * Update bringYourOwnFormatter documentation to match new formatter --------- Co-authored-by: erikayao93 <[email protected]> * chore(logger): PowertoolsLogFormatter docstring and variable naming update (aws-powertools#1585) * Updated formatAttributes for additional parameters and LogItem return type * Updated the unit tests to pass with new formatter * Updated Powertool named objects to Powertools * Updated tests to match new naming consistency * Updated for tests for new naming consistency * Updated formatter for new design decisions * Update Logger for ephemeral attributes * Update bringYourOwnFormatter documentation to match new formatter * Fixed incorrect return type, renamed variable for consistency * chore(maintenance): bump dependencies & drop nodejs14x (aws-powertools#1687) * chore: update release script to mark all utilities as alpha * chore: restore version to ease conflicts * chore: release version change * chore: release version change * chore(maintenance): remove `createLogger` and `createTracer` helpers (aws-powertools#1722) * chore(maintenance): bump dependencies & drop nodejs14x (aws-powertools#1687) * chore: add pre-release script * chore: restore deps * chore: added v2 shim * chore(maintenance): remove logger and tracer helper function * chore: remove imports * chore: fix deps & versions * tests: moved unit tests * tests: move logger tests * chore: added v2 shim * chore: added v2 shim * feat(logger): add esmodule support (aws-powertools#1734) * feat(logger): add esm build output * fix(Logger): Remove barrel files update references * test(Logger): update jest/ts-jest to use ESM * chore(Logger): remove unused lodash.merge * fix(logger): reinstate lodash.merge * chore(logger): revert TS assertion * chore(logger): revert format changes * chore(logger): update postbuild to remove incremental tsbuildinfo files * fix(logger): correct reference to types output * feat(logging): add middleware export * chore(logger): replace postbuild script with echo statement * feat(logger): add typesVersions property and barrel files to /types * chore(logger): file not used, can be added back if needed * chore(logger): add space back to README * chore(logger): revert space in README * feat(commons): add esmodule support (aws-powertools#1735) * chore(logger): adapt logger to commons exports * feat(commons): add esmodule support * chore: address sonar findings * chore(commons): exported version * chore: fixed imports in examples * chore(parameters): fixed imports * chore(metrics): fixed imports * chore(tracer): fixed imports * chore(idempotency): fixed imports * chore(commons): test coverage * chore(batch): fix imports * feat(parameters): add esmodule support (aws-powertools#1736) * feat(batch): add esmodule support (aws-powertools#1737) * feat(internal): add esmodule support (aws-powertools#1738) * feat(testing): add esmodule support * chore(all): update imports * feat(metrics): add esmodule support (aws-powertools#1739) * feat(tracer): add esmodule support (aws-powertools#1741) * feat(tracer): add esmodule support * chore(docs): update imports * feat(idempotency): add esmodule support (aws-powertools#1743) * feat(idempotency): add esmodule support * chore(metrics): fix import * chore(ci): v2 release line * chore(ci): fix alpha versioning pre-release * docs(maintenance): add processes tab (aws-powertools#1747) * docs(maintenance): update mkdocs to support tabs * chore(ci): add parallel test npm script * chore(ci): add jest command * docs(maintenance): add testing page to navbar * docs(maintenance): add contributing info * chore: update roadmap * chore: update release drafter workflow to allow for manual trigger * fix formatting * docs: maintainers handbook * chore: link to new location * fix links * Update docs/maintainers.md Co-authored-by: Alexander Schueren <[email protected]> --------- Co-authored-by: Alexander Schueren <[email protected]> * chore(tracer): update warning to better format segment name (aws-powertools#1750) * chore(tracer): update warning in Tracer to better format segment name * chore: linting * chore(internal): remove outdated notice files (aws-powertools#1752) * chore(maintenance): set `removeComments` to` false` in `tsconfig.json` (aws-powertools#1754) * chore(docs): add invisible unicode char to decorator docs (aws-powertools#1755) * chore: remove extra comma * chore(docs): upgrade doc intro * chore(ci): add workflow to publish v2 docs on merge (aws-powertools#1756) * chore(docs): upgrade doc intro * chore(ci): remove mike commands * chore(ci): upgrade mkdocs * feat(logger): align sampling debug logs feature implementation with the other runtimes (aws-powertools#1744) * test(logger): remove logsSampled field, add default sampleRateValue * test(logger): add tests for sampling debug logs feature * feat(logger): change implementation to make sampling decision at per-function level * refactor(logger): remove redundant createLogger method * refactor(logger): remove getSampleRateValue method * test(logger): improve tests * refactor(logger): return createLogger() back with the detailed comment of the method importance * test(logger): add constructor/custom config/env var priority tests for sampling rate feature, improve description * refactor(logger): address review comments * feat(logger): add refreshSampleRateCalculation method and tests * test(logger): adjust end-to-end tests * chore(logger): refactor types and interfaces (aws-powertools#1758) * chore(logger): refactor types and interfaces * chore: grouped type files * chore: fix code smell * chore: fix ci * chore: fix ci * chore(maintenance): bump Middy v4 & run tests (aws-powertools#1760) * chore(parameters): fix esm bundling * chore(parameters): refactor provider constructor to init client as needed (aws-powertools#1757) * chore(parameters): refactor provider constructor to init client as needed * chore(parameters): moved client instrumentation up in baseprovider * chore(parameters): fix code smells * chore(parameters): fix code smells * chore(parameters): change declare client param * chore(commons): update Powertools UA middleware detection (aws-powertools#1762) * chore(commons): fix double ua detection * chore(commons): fix unit test * chore(layers) widen version check in e2e * chore(maintenance): enable `isolatedModules` and isolate cache (aws-powertools#1765) * chore(layers) widen version check in e2e * chore(maintenance): enable isolatedModules * chore: remove redundant comments from tsconfig * chore: changed path of tsbuild cache * fix: idempotency types * chore(idempotency): refactor aws sdk init logic (aws-powertools#1768) * build(tracer): bump aws-xray-sdk-core to latest * build(maintenance): bump aws sdk dev dependencies * chore(logger): set default UTC timezone (aws-powertools#1775) * chore(parameters): add export types * chore(logger): set default utc timezone * chore(logger): pass down envvarsservice to log formatter * feat(parser): add built-in schemas (aws-powertools#1788) * add dynamodb schema * add alb * add parser to v2 build * fix test * add alb * add built-in schema * add more tests for schemas * remove index export * add cloudwatch with base64 zlip transform * add throw test case * formatting * add kafka schema * restructured tests * add vpc lattice and lattice v2 * s3 event notification should extend eventbridge * s3 sqs should extend from sqs * simplify cloudwatch extract from string * keep message as string, instead of empty object * fix detail type of eb and field names * remove duplicated entries * fix homepage URL in readme * improved test coverage * key and value are always present * cleanup unnecessary definitions, widen peerDep version req * Update packages/parser/src/schemas/cloudwatch.ts Co-authored-by: Andrea Amorosi <[email protected]> * clean up events, some fields are imaginary * fix api gw * fix broken IP addresses in examples * add more tests to api gw * fix apigw2 add more tests * add optional scopes to apigwv2 * add optional field back to api gw, stricter methods for vpc lattice * add test for messageId refinement * remove redundant entry * fix sqs * add dmarcPolicy for ses * added tests * moved cw function from kinesis, fix imports * add parser to build step in ci * use any safely here * removed console logs * name, add datetime to strings * narrow string to datetime * refine to url * imports, remove try/catch * add .js extension to imports * moved comment, fixed path * rename event filename to fix events --------- Co-authored-by: Andrea Amorosi <[email protected]> * feat(parser): add schema envelopes (aws-powertools#1815) * first envelope * add abstract class * add tests * add more tests * fix tests * add envelopes * add middy parser * minor schema changes * add more envelopes and tests, refactored utils to autocomplete event files * simplified check * remove middleware from this branch * refactored from class to function envelopes * removed parser tests, should be in another branch * add parser to pre push * consistent naming * feat(parser): implement middy parser middleware (aws-powertools#1823) * add middy middleware * add type to imports * remove schema type, stick with unkown * feat(parser): implement parser decorator (aws-powertools#1831) * feat(parser): add types for built-in schemas (aws-powertools#1838) * add types for built-in schemas * fixed imports * only use top level schema * chore(parser): add parser subpath exports to package.json (aws-powertools#2179) * add exports and type version to package json, including index.js * use index.js as import for coverage * use package lock from main * fix envelope path and add types to exports * use explicit exports instead of * * import type * make export types explicit * adjust imports in tests for coverage, removed unused exports * remove duplicate imports * feat(parser): implement `safeParse` option (aws-powertools#2244) * first draft on safeParse with major refactoring * add safeParse * fixed sns tests * bump coverage * remove throw error and return ParsedResult * remove one level to reduce complexity score * make static methods readonly * simplified cryptic ternary operation into something readble * Update packages/parser/src/parserDecorator.ts Co-authored-by: Andrea Amorosi <[email protected]> * merged * simplify export * add invisible character for decorator rendering * fix docs and tests * Update packages/parser/src/parserDecorator.ts Co-authored-by: Andrea Amorosi <[email protected]> * add comment with description * remove context * remove unintentional safeParse export * add examples to parse standalone function --------- Co-authored-by: Andrea Amorosi <[email protected]> * refresh package lock after merge * docs(parser): add docs for parser utility (aws-powertools#1835) * WIP: parser * fix test imports * remove unnecessary exports * add custom validation * remove unnecessary export * add warning * remove duplicate imports * add types and error handlig * remove comment from annotations * minor changes * revert merge changes * merged package-lock * Update docs/utilities/parser.md Co-authored-by: Andrea Amorosi <[email protected]> * Update docs/utilities/parser.md Co-authored-by: Andrea Amorosi <[email protected]> * adjust imports to new implementation * add safeParse * fixed line highlight * typo * revert index.md, add private scope to snippets packagef * Update docs/utilities/parser.md Co-authored-by: Andrea Amorosi <[email protected]> * add parser to main, fixed zod install command * fix callout indent * fix tooltip --------- Co-authored-by: Andrea Amorosi <[email protected]> * feat(parser): add custom parse error (aws-powertools#2339) * chore: remove rebase leftovers * docs(parser): add utility readme --------- Co-authored-by: Alexander Melnyk <[email protected]> Co-authored-by: Alexander Melnyk <[email protected]> Co-authored-by: Erika Yao <[email protected]> Co-authored-by: erikayao93 <[email protected]> Co-authored-by: Ant Stanley <[email protected]> Co-authored-by: Sergei Cherniaev <[email protected]>
1 parent 9bf9ac8 commit 4f526ec

File tree

196 files changed

+9652
-12
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

196 files changed

+9652
-12
lines changed

.github/scripts/release_patch_package_json.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -94,4 +94,4 @@ const betaPackages = [];
9494
} catch (err) {
9595
throw err;
9696
}
97-
})();
97+
})();

.gitignore

+1-1
Original file line numberDiff line numberDiff line change
@@ -46,4 +46,4 @@ tmp
4646

4747
# TS build files
4848
tsconfig.tsbuildinfo
49-
.tsbuildinfo
49+
.tsbuildinfo

.husky/pre-push

+2-1
Original file line numberDiff line numberDiff line change
@@ -4,4 +4,5 @@ npm t \
44
-w packages/metrics \
55
-w packages/tracer \
66
-w packages/idempotency \
7-
-w packages/parameters
7+
-w packages/parameters \
8+
-w packages/parser

.npmignore

+1-2
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
src
22
tests
3-
jest.config.js
43
tsconfig.json
54
.vscode
65
.github
@@ -13,7 +12,7 @@ coverage
1312
tslint.json
1413
tsconfig.json
1514
MakeFile
16-
jest.config.js
15+
jest.config.cjs
1716
.npmignore
1817
.eslintignore
1918
.huskyrc.js

docs/index.md

+3-3
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,6 @@ You can use Powertools for AWS Lambda (TypeScript) by installing it with your fa
6161
| **[Parameters (AppConfig)](./utilities/parameters.md#install)** | **`npm i @aws-lambda-powertools/parameters @aws-sdk/client-appconfigdata`**{.copyMe}:clipboard: | |
6262
| **[Parser](./utilities/parser.md#install)** | **`npm i @aws-lambda-powertools/parser zod@~3`**{.copyMe}:clipboard: | |
6363

64-
6564
=== "Lambda Layer"
6665

6766
You can add our layer both in the [AWS Lambda Console _(under `Layers`)_](https://eu-west-1.console.aws.amazon.com/lambda/home#/add/layer){target="_blank"}, or via your favorite infrastructure as code framework with the ARN value.
@@ -325,11 +324,12 @@ Core utilities such as Tracing, Logging, and Metrics will be available across al
325324
| [Parameters](./utilities/parameters.md) | High-level functions to retrieve one or more parameters from AWS SSM Parameter Store, AWS Secrets Manager, AWS AppConfig, and Amazon DynamoDB |
326325
| [Idempotency](./utilities/idempotency.md) | Class method decorator, Middy middleware, and function wrapper to make your Lambda functions idempotent and prevent duplicate execution based on payload content. |
327326
| [Batch Processing](./utilities/batch.md) | Utility to handle partial failures when processing batches from Amazon SQS, Amazon Kinesis Data Streams, and Amazon DynamoDB Streams. |
327+
| [Parser](./utilities/parser.md) | Utility to parse and validate AWS Lambda event payloads using Zod, a TypeScript-first schema declaration and validation library. |
328328

329329
## Environment variables
330330

331331
???+ info
332-
Explicit parameters take precedence over environment variables
332+
Explicit parameters take precedence over environment variables
333333

334334
| Environment variable | Description | Utility | Default |
335335
| -------------------------------------------- | ------------------------------------------------------------------------------------------------------------- | --------------------------------------- | ------------------- |
@@ -438,4 +438,4 @@ These are our core principles to guide our decision making.
438438
- __Keep it lean__. Additional dependencies are carefully considered for security and ease of maintenance, and prevent negatively impacting startup time.
439439
- __We strive for backwards compatibility__. New features and changes should keep backwards compatibility. If a breaking change cannot be avoided, the deprecation and migration process should be clearly defined.
440440
- __We work backwards from the community__. We aim to strike a balance of what would work best for 80% of customers. Emerging practices are considered and discussed via Requests for Comment (RFCs)
441-
- __Progressive__. Utilities are designed to be incrementally adoptable for customers at any stage of their Serverless journey. They follow language idioms and their community’s common practices.
441+
- __Progressive__. Utilities are designed to be incrementally adoptable for customers at any stage of their Serverless journey. They follow language idioms and their community’s common practices.

docs/snippets/package.json

+3-1
Original file line numberDiff line numberDiff line change
@@ -34,10 +34,12 @@
3434
"@aws-sdk/client-secrets-manager": "^3.554.0",
3535
"@aws-sdk/client-ssm": "^3.554.0",
3636
"@aws-sdk/util-dynamodb": "^3.554.0",
37+
"@middy/core": "^4.7.0",
3738
"aws-sdk": "^2.1598.0",
3839
"aws-sdk-client-mock": "^4.0.0",
3940
"aws-sdk-client-mock-jest": "^4.0.0",
4041
"axios": "^1.6.8",
41-
"hashi-vault-js": "^0.4.14"
42+
"hashi-vault-js": "^0.4.14",
43+
"zod": "^3.22.4"
4244
}
4345
}

docs/snippets/parser/decorator.ts

+35
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
import type { Context } from 'aws-lambda';
2+
import type { LambdaInterface } from '@aws-lambda-powertools/commons/types';
3+
import { parser } from '@aws-lambda-powertools/parser';
4+
import { z } from 'zod';
5+
import { Logger } from '@aws-lambda-powertools/logger';
6+
7+
const logger = new Logger();
8+
9+
const orderSchema = z.object({
10+
id: z.number().positive(),
11+
description: z.string(),
12+
items: z.array(
13+
z.object({
14+
id: z.number().positive(),
15+
quantity: z.number(),
16+
description: z.string(),
17+
})
18+
),
19+
optionalField: z.string().optional(),
20+
});
21+
22+
type Order = z.infer<typeof orderSchema>;
23+
24+
class Lambda implements LambdaInterface {
25+
@parser({ schema: orderSchema })
26+
public async handler(event: Order, _context: Context): Promise<void> {
27+
// event is now typed as Order
28+
for (const item of event.items) {
29+
logger.info('Processing item', { item });
30+
}
31+
}
32+
}
33+
34+
const myFunction = new Lambda();
35+
export const handler = myFunction.handler.bind(myFunction);
+36
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
import type { Context } from 'aws-lambda';
2+
import type { LambdaInterface } from '@aws-lambda-powertools/commons/types';
3+
import { parser } from '@aws-lambda-powertools/parser';
4+
import { z } from 'zod';
5+
import { EventBridgeEnvelope } from '@aws-lambda-powertools/parser/envelopes';
6+
import { Logger } from '@aws-lambda-powertools/logger';
7+
8+
const logger = new Logger();
9+
10+
const orderSchema = z.object({
11+
id: z.number().positive(),
12+
description: z.string(),
13+
items: z.array(
14+
z.object({
15+
id: z.number().positive(),
16+
quantity: z.number(),
17+
description: z.string(),
18+
})
19+
),
20+
optionalField: z.string().optional(),
21+
});
22+
23+
type Order = z.infer<typeof orderSchema>;
24+
25+
class Lambda implements LambdaInterface {
26+
@parser({ schema: orderSchema, envelope: EventBridgeEnvelope }) // (1)!
27+
public async handler(event: Order, _context: Context): Promise<void> {
28+
// event is now typed as Order
29+
for (const item of event.items) {
30+
logger.info('Processing item', item); // (2)!
31+
}
32+
}
33+
}
34+
35+
const myFunction = new Lambda();
36+
export const handler = myFunction.handler.bind(myFunction);

docs/snippets/parser/envelopeMiddy.ts

+37
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
import type { Context } from 'aws-lambda';
2+
import { parser } from '@aws-lambda-powertools/parser/middleware';
3+
import { z } from 'zod';
4+
import middy from '@middy/core';
5+
import { EventBridgeEnvelope } from '@aws-lambda-powertools/parser/envelopes';
6+
import { Logger } from '@aws-lambda-powertools/logger';
7+
8+
const logger = new Logger();
9+
10+
const orderSchema = z.object({
11+
id: z.number().positive(),
12+
description: z.string(),
13+
items: z.array(
14+
z.object({
15+
id: z.number().positive(),
16+
quantity: z.number(),
17+
description: z.string(),
18+
})
19+
),
20+
optionalField: z.string().optional(),
21+
});
22+
23+
type Order = z.infer<typeof orderSchema>;
24+
25+
const lambdaHandler = async (
26+
event: Order,
27+
_context: Context
28+
): Promise<void> => {
29+
for (const item of event.items) {
30+
// item is parsed as OrderItem
31+
logger.info('Processing item', { item });
32+
}
33+
};
34+
35+
export const handler = middy(lambdaHandler).use(
36+
parser({ schema: orderSchema, envelope: EventBridgeEnvelope })
37+
);
+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
{
2+
"version": "0",
3+
"id": "6a7e8feb-b491-4cf7-a9f1-bf3703467718",
4+
"detail-type": "OrderPurchased",
5+
"source": "OrderService",
6+
"account": "111122223333",
7+
"time": "2020-10-22T18:43:48Z",
8+
"region": "us-west-1",
9+
"resources": ["some_additional"],
10+
"detail": {
11+
"id": 10876546789,
12+
"description": "My order",
13+
"items": [
14+
{
15+
"id": 1015938732,
16+
"quantity": 1,
17+
"description": "item xpto"
18+
}
19+
]
20+
}
21+
}

docs/snippets/parser/extend.ts

+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
import type { Context } from 'aws-lambda';
2+
import type { LambdaInterface } from '@aws-lambda-powertools/commons/types';
3+
import { parser } from '@aws-lambda-powertools/parser';
4+
import { z } from 'zod';
5+
import { EventBridgeSchema } from '@aws-lambda-powertools/parser/schemas';
6+
import { Logger } from '@aws-lambda-powertools/logger';
7+
8+
const logger = new Logger();
9+
10+
const orderSchema = z.object({
11+
id: z.number().positive(),
12+
description: z.string(),
13+
items: z.array(
14+
z.object({
15+
id: z.number().positive(),
16+
quantity: z.number(),
17+
description: z.string(),
18+
})
19+
),
20+
optionalField: z.string().optional(),
21+
});
22+
23+
const orderEventSchema = EventBridgeSchema.extend({
24+
detail: orderSchema, // (1)!
25+
});
26+
27+
type OrderEvent = z.infer<typeof orderEventSchema>;
28+
29+
class Lambda implements LambdaInterface {
30+
@parser({ schema: orderEventSchema }) // (2)!
31+
public async handler(event: OrderEvent, _context: Context): Promise<void> {
32+
for (const item of event.detail.items) {
33+
// process OrderItem
34+
logger.info('Processing item', { item }); // (3)!
35+
}
36+
}
37+
}
38+
39+
const myFunction = new Lambda();
40+
export const handler = myFunction.handler.bind(myFunction);

docs/snippets/parser/manual.ts

+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
import type { Context } from 'aws-lambda';
2+
import { z } from 'zod';
3+
import { EventBridgeEnvelope } from '@aws-lambda-powertools/parser/envelopes';
4+
import { EventBridgeSchema } from '@aws-lambda-powertools/parser/schemas';
5+
import type { EventBridgeEvent } from '@aws-lambda-powertools/parser/types';
6+
import { Logger } from '@aws-lambda-powertools/logger';
7+
8+
const logger = new Logger();
9+
10+
const orderSchema = z.object({
11+
id: z.number().positive(),
12+
description: z.string(),
13+
items: z.array(
14+
z.object({
15+
id: z.number().positive(),
16+
quantity: z.number(),
17+
description: z.string(),
18+
})
19+
),
20+
optionalField: z.string().optional(),
21+
});
22+
type Order = z.infer<typeof orderSchema>;
23+
24+
export const handler = async (
25+
event: EventBridgeEvent,
26+
_context: Context
27+
): Promise<void> => {
28+
const parsedEvent = EventBridgeSchema.parse(event); // (1)!
29+
logger.info('Parsed event', parsedEvent);
30+
31+
const orders: Order = EventBridgeEnvelope.parse(event, orderSchema); // (2)!
32+
logger.info('Parsed orders', orders);
33+
};
+35
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
import type { Context } from 'aws-lambda';
2+
import { z } from 'zod';
3+
import { EventBridgeEnvelope } from '@aws-lambda-powertools/parser/envelopes';
4+
import { EventBridgeSchema } from '@aws-lambda-powertools/parser/schemas';
5+
import type { EventBridgeEvent } from '@aws-lambda-powertools/parser/types';
6+
import { Logger } from '@aws-lambda-powertools/logger';
7+
8+
const logger = new Logger();
9+
10+
const orderSchema = z.object({
11+
id: z.number().positive(),
12+
description: z.string(),
13+
items: z.array(
14+
z.object({
15+
id: z.number().positive(),
16+
quantity: z.number(),
17+
description: z.string(),
18+
})
19+
),
20+
optionalField: z.string().optional(),
21+
});
22+
23+
export const handler = async (
24+
event: EventBridgeEvent,
25+
_context: Context
26+
): Promise<void> => {
27+
const parsedEvent = EventBridgeSchema.safeParse(event); // (1)!
28+
parsedEvent.success
29+
? logger.info('Event parsed successfully', parsedEvent.data)
30+
: logger.error('Event parsing failed', parsedEvent.error);
31+
const parsedEvenlope = EventBridgeEnvelope.safeParse(event, orderSchema); // (2)!
32+
parsedEvenlope.success
33+
? logger.info('Event envelope parsed successfully', parsedEvenlope.data)
34+
: logger.error('Event envelope parsing failed', parsedEvenlope.error);
35+
};

docs/snippets/parser/middy.ts

+36
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
import type { Context } from 'aws-lambda';
2+
import { parser } from '@aws-lambda-powertools/parser/middleware';
3+
import { z } from 'zod';
4+
import middy from '@middy/core';
5+
import { Logger } from '@aws-lambda-powertools/logger';
6+
7+
const logger = new Logger();
8+
9+
const orderSchema = z.object({
10+
id: z.number().positive(),
11+
description: z.string(),
12+
items: z.array(
13+
z.object({
14+
id: z.number().positive(),
15+
quantity: z.number(),
16+
description: z.string(),
17+
})
18+
),
19+
optionalField: z.string().optional(),
20+
});
21+
22+
type Order = z.infer<typeof orderSchema>;
23+
24+
const lambdaHandler = async (
25+
event: Order,
26+
_context: Context
27+
): Promise<void> => {
28+
for (const item of event.items) {
29+
// item is parsed as OrderItem
30+
logger.info('Processing item', { item });
31+
}
32+
};
33+
34+
export const handler = middy(lambdaHandler).use(
35+
parser({ schema: orderSchema })
36+
);

docs/snippets/parser/refine.ts

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
import { z } from 'zod';
2+
3+
const orderItemSchema = z.object({
4+
id: z.number().positive(),
5+
quantity: z.number(),
6+
description: z.string(),
7+
});
8+
9+
export const orderSchema = z
10+
.object({
11+
id: z.number().positive(),
12+
description: z.string(),
13+
items: z.array(orderItemSchema).refine((items) => items.length > 0, {
14+
message: 'Order must have at least one item', // (1)!
15+
}),
16+
optionalField: z.string().optional(),
17+
})
18+
.refine((order) => order.id > 100 && order.items.length > 100, {
19+
message:
20+
'All orders with more than 100 items must have an id greater than 100', // (2)!
21+
});

0 commit comments

Comments
 (0)