|
| 1 | +import { |
| 2 | + IdempotencyConfig, |
| 3 | + makeIdempotent, |
| 4 | +} from '@aws-lambda-powertools/idempotency'; |
| 5 | +import { DynamoDBPersistenceLayer } from '@aws-lambda-powertools/idempotency/dynamodb'; |
| 6 | +import { SchemaType, kafkaConsumer } from '@aws-lambda-powertools/kafka'; |
| 7 | +import type { SchemaConfig } from '@aws-lambda-powertools/kafka/types'; |
| 8 | +import { Logger } from '@aws-lambda-powertools/logger'; |
| 9 | +import { User } from './samples/user.es6.generated.js'; // protobuf generated class |
| 10 | + |
| 11 | +const logger = new Logger({ serviceName: 'kafka-consumer' }); |
| 12 | +const persistenceStore = new DynamoDBPersistenceLayer({ |
| 13 | + tableName: 'IdempotencyTable', |
| 14 | +}); |
| 15 | + |
| 16 | +const schemaConfig = { |
| 17 | + value: { |
| 18 | + type: SchemaType.PROTOBUF, |
| 19 | + schema: User, |
| 20 | + }, |
| 21 | +} satisfies SchemaConfig; |
| 22 | + |
| 23 | +const processRecord = makeIdempotent( |
| 24 | + async (user, topic, partition, offset) => { |
| 25 | + logger.info('processing user', { |
| 26 | + userId: user.id, |
| 27 | + meta: { |
| 28 | + topic, |
| 29 | + partition, |
| 30 | + offset, |
| 31 | + }, |
| 32 | + }); |
| 33 | + |
| 34 | + // ...your business logic here |
| 35 | + |
| 36 | + return { |
| 37 | + success: true, |
| 38 | + userId: user.id, |
| 39 | + }; |
| 40 | + }, |
| 41 | + { |
| 42 | + persistenceStore, |
| 43 | + config: new IdempotencyConfig({ |
| 44 | + eventKeyJmesPath: `topic & '-' & partition & '-' & offset`, |
| 45 | + }), |
| 46 | + } |
| 47 | +); |
| 48 | + |
| 49 | +export const handler = kafkaConsumer(async (event, _context) => { |
| 50 | + for (const { value, topic, partition, offset } of event.records) { |
| 51 | + await processRecord(value, topic, partition, offset); |
| 52 | + } |
| 53 | +}, schemaConfig); |
0 commit comments