import { Duration, CustomResource } from 'aws-cdk-lib'; import * as path from 'path'; import * as iam from 'aws-cdk-lib/aws-iam'; import * as lambda from 'aws-cdk-lib/aws-lambda'; import * as cr from 'aws-cdk-lib/custom-resources'; import { GlobalSecondaryIndexProps } from 'aws-cdk-lib/aws-dynamodb'; import { Construct } from 'constructs'; import { NodejsFunction } from 'aws-cdk-lib/aws-lambda-nodejs'; const __filename = import.meta.url.replace(/^file:/, ''); const __dirname = path.dirname(__filename); export interface TableIndexesProps { tableName: string; indexes: GlobalSecondaryIndexProps[]; } export class TableIndexes extends Construct { constructor(scope: Construct, id: string, props: TableIndexesProps) { super(scope, id); const onEvent = new NodejsFunction(this, 'TableIndexesHandler', { runtime: lambda.Runtime.NODEJS_22_X, handler: 'handler', entry: path.join(__dirname, 'handler-lambda.ts'), timeout: Duration.minutes(15), }); onEvent.addToRolePolicy(new iam.PolicyStatement({ actions: [ 'dynamodb:UpdateTable', 'dynamodb:DescribeTable' ], resources: [ `arn:aws:dynamodb:*:*:table/${props.tableName}` ], })); const provider = new cr.Provider(this, 'TableIndexesProvider', { onEventHandler: onEvent, }); new CustomResource(this, 'TableIndexesCustomResource', { serviceToken: provider.serviceToken, properties: { TableName: props.tableName, GlobalSecondaryIndexes: props.indexes, }, }); } }