Skip to content

Instantly share code, notes, and snippets.

@markilott
Last active October 29, 2022 03:16
Show Gist options
  • Save markilott/5b416440836efd60d44fdb56a6b5526c to your computer and use it in GitHub Desktop.
Save markilott/5b416440836efd60d44fdb56a6b5526c to your computer and use it in GitHub Desktop.
import { Duration, RemovalPolicy } from 'aws-cdk-lib';
import { AttributeType, BillingMode, Table } from 'aws-cdk-lib/aws-dynamodb';
import { Construct } from 'constructs';
type CustomDynamoTableProps = {
/** Table Partition Key */
partitionKey: string,
/** Optional Sort Key */
sortKey?: string,
/** Table Name */
tableName: string,
/** Retain the table on stack deletion */
retainTable?: boolean,
/**
* Enable TTL Field (ExpiryTime)
* @default true
*/
enableTtl?: boolean,
};
/**
* Creates a DynamoDB table with standard settings.
*/
export class CustomDynamoTable extends Construct {
/** DynamoDb Table with standard settings */
public table: Table;
/**
* @param {Construct} scope
* @param {string} id
* @param {CustomDynamoTableProps} props
*/
constructor(scope: Construct, id: string, props: CustomDynamoTableProps) {
super(scope, id);
const {
partitionKey,
sortKey,
tableName,
retainTable,
enableTtl = true,
} = props;
// DynamoDb Table =====================================
const table = new Table(this, tableName, {
tableName,
billingMode: BillingMode.PAY_PER_REQUEST,
partitionKey: { name: partitionKey, type: AttributeType.STRING },
sortKey: (sortKey) ? { name: sortKey, type: AttributeType.STRING } : undefined,
removalPolicy: (retainTable) ? RemovalPolicy.RETAIN : RemovalPolicy.DESTROY,
timeToLiveAttribute: (enableTtl) ? 'ExpiryTime' : undefined,
});
this.table = table;
}
}
/**
* Create a table with the standard settings and a sort key only is as simple as:
*/
new CustomDynamoTable(this, 'DataTable', {
tableName: 'MyTable',
partitionKey: 'ItemId',
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment