Home > Back-end >  AWS CDK - Declare input variables from StackProps
AWS CDK - Declare input variables from StackProps

Time:12-01

I've started to use the AWS CDK recently, and I've faced an issue. I would like to have an ability to define custom input variables, so end users who are using my AWS CDK, were able to define inputs by them selves, without editing whole code. I've managed to adopt standard types like; string, number, booleans etc, however I do not quite understand how to do the same with custom types, for example:

I've tried to create an AWS DynamoDB, firstly I've defined an interface then make sure, that end user will precisely input required data

Here is my interface:

export interface IDynamoDB extends StackProps {
    tableClass:       unknow,
    billingMode:      unknow
    sortKeyName:      string,
    sortKeyType:      unknow,
    partitionKeyName: string,
    partitionKeyType: unknow
    inTimeRecovery:   boolean
}

Here is my class:

export class Ddb extends Stack {
    constructor(scope: Construct, name: string, props: IDynamoDB) {
        super(scope, name, props);


        const table = new ddb.Table(this, name, {
            tableName:      name,
            tableClass:     ddb.TableClass.STANDARD,
            billingMode:    ddb.BillingMode.PROVISIONED,
            sortKey: {
                    name: props.sortKeyName,
                    type: ddb.AttributeType.NUMBER
            },
            partitionKey: {
                    name: props.partitionKeyName,
                    type: ddb.AttributeType.STRING
            },
        })
    }
}

Imports

import { Construct } from 'constructs';
import { Stack, StackProps } from 'aws-cdk-lib';
import * as ddb from 'aws-cdk-lib/aws-dynamodb';

My problem with my interface, as you can see I've putted unknown as a type, and I don't know how to make more easier. At the end I would like to be able to just put a string for example:

ddb.TableClass.STANDARD = standartTableClass

I hope I've managed to explain my problem

CodePudding user response:

Normally your props would have the same ddb Enum types as the construct (see tableClass below). However, as you are optimizing for short values per your comment, you could define your props with the Enum's string values and lookup the type in your constructor (see billingMode).

export interface IDynamoDB extends StackProps {
  tableClass: ddb.TableClass;
  billingMode: "PROVISIONED" | "PAY_PER_REQUEST"; // string values of the Typescript Enum type
  sortKeyName: string;
  sortKeyType: ddb.AttributeType;
  partitionKeyName: string;
  partitionKeyType: ddb.AttributeType;
  inTimeRecovery: boolean;
}

table constructor:

tableClass:     props.tableClass,
billingMode:    ddb.BillingMode[props.billingMode], // map the enum

Notes of caution about the billingMode approach: (1) you may want to apply stricter checks and (2) your users will lose intellisense documentation context.

  • Related