# StackSpot DynamoDB Table construct library

A CDK construct for Typescript that can be used to create DynamoDB Table, give permissions for lambdas functions and generate commons commands.

The class _StackSpotDynamoDBTable_ in the construct extends the original CDK DynamoDB Table, we're extending it to facilitate the integration between [StackSpot OpenAPI contract first API Gateway + Lambda construct library](https://github.com/Stack-Spot/domainservices-cdk-openapi-lambda).

## Prerequisites

- NodeJS 14.x - <https://nodejs.org>
- AWS account properly configured - <https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-configure.html>
- AWS CDK CLI - <https://docs.aws.amazon.com/cdk/latest/guide/cli.html>

## Optional (recommended) development tools

- Visual Studio Code (IDE) - <https://code.visualstudio.com/>
- Prettier VSCode extension (Code formatter) - <https://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode>
- Jest Runner VSCode extension (Runs jest tests from IDE) - <https://marketplace.visualstudio.com/items?itemName=firsttris.vscode-jest-runner>

## How to build library package

- To build the library package clone the repository and run npm scripts

```
git clone git@github.com:Stack-Spot/domainservices-cdk-dynamodb.git
cd domainservices-cdk-dynamodb
npm install
npm run build
npm run package
```

- The library will be built and package `dynamodb@<version>.jsii.tgz` will be generated in `dist/js` folder

## Quick start

The example bellow will create a simple CDK App using TypeScript and will create a DynamoDB Table.

### 1. Init a CDK app using the cli

```
mkdir hello-world-app
cd hello-world-app
cdk init --language=typescript
```

### 2. Add dependencies

```
npm install @aws-cdk/aws-dynamodb @stackspot/cdk-component-dynamodb-typescript
```

### 3. Using the construct

Open the file `lib/hello-world-app-stack.ts` that was generated by the CDK CLI like bellow:

```typescript
import * as cdk from '@aws-cdk/core';
import { StackSpotDynamoDBTable } from '@stackspot/cdk-component-dynamodb-typescript';
import { AttributeType } from '@aws-cdk/aws-dynamodb';

export class HelloWorldAppStack extends cdk.Stack {
  constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) {
    super(scope, id, props);

    new StackSpotDynamoDBTable(this, 'HelloWorldTable', {
      tableConfiguration: {
        partitionKey: { name: 'pk', type: AttributeType.STRING },
      },
    });
  }
}
```

### 4. Execute CDK bootstrap to prepare stack

```
cdk bootstrap --profile <your-aws-profile>
```

If you have permissions problems related to S3 public access block configuration permissions on bootstrap you could add the option `--public-access-block-configuration false` to the bootstrap command as shown below:

```
cdk bootstrap --profile <your-aws-profile> --public-access-block-configuration false
```

### 5. Creating GSI

To create any GSI, add `gsis` property array:

```typescript
import * as cdk from '@aws-cdk/core';
import { StackSpotDynamoDBTable } from '@stackspot/cdk-component-dynamodb-typescript';
import { AttributeType } from '@aws-cdk/aws-dynamodb';

export class HelloWorldAppStack extends cdk.Stack {
  constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) {
    super(scope, id, props);

    new StackSpotDynamoDBTable(this, 'HelloWorldTable', {
      tableConfiguration: {
        partitionKey: { name: 'pk', type: AttributeType.STRING },
        sortKey: { name: 'sk', type: AttributeType.STRING },
      },
      gsis: [
        {
          indexName: 'my-gsi-index',
          partitionKey: { name: 'sk', type: AttributeType.STRING },
        },
      ],
    });
  }
}
```

### 6. Build and deploy the project to create the table

Run `npm run build` and `cdk deploy`.

Check in AWS Console the DynamoDB table created.

## Integrating with StackSpot OpenAPI Typescript Lambda construct

The best part of this construct is to facilitate the integration between the table and lambdas created by [StackSpot OpenAPI contract first API Gateway + Lambda construct library](https://github.com/stack-spot/domainservices-cdk-openapi-lambda).

Check the [StackSpot OpenAPI contract first API Gateway + Lambda construct library](https://github.com/stack-spot/domainservices-cdk-openapi-lambda) docs to learn more.

Then you can integrate the constructs using `lambdasConfiguration` properties:

```typescript
const lambdas = new StackSpotOpenApiServices(this, 'HelloWorldApi', {
  specPath: 'spec/hello-world.yaml',
});

new StackSpotDynamoDBTable(this, 'HelloWorldTable', {
  tableConfiguration: {
    partitionKey: { name: 'pk', type: AttributeType.STRING },
  },
  lambdasConfiguration: {
    lambdasById: lambdas.backendLambdas,
    tableNameEnvironmentVariable: 'MY_DYNAMO_TABLE_NAME',
  },
});
```

Now all the `lambdas` will have permissions to read and write to the DynamoDB table.

### Set readOnly lambda permission

To set readOnly permission to your lambda use `readOnly` property with the `operation-id` name defined in your OpenAPI Spec:

```typescript
const lambdas = new StackSpotOpenApiServices(this, 'HelloWorldApi', {
  specPath: 'spec/hello-world.yaml',
});

new StackSpotDynamoDBTable(this, 'HelloWorldTable', {
  tableConfiguration: {
    partitionKey: { name: 'pk', type: AttributeType.STRING },
  },
  lambdasConfiguration: {
    lambdasById: lambdas.backendLambdas,
    tableNameEnvironmentVariable: 'MY_DYNAMO_TABLE_NAME',
    readOnly: ['list-hello', 'get-hello'],
  },
});
```

## Generate DynamoDB commons commands

Some commons commands (insert, queries, updates and deletes) are commons and required for all sort off applications, so this construct is generating some helper functions to help you with this task.

To let the construct generate the code, set the `StackSpotDynamoDBTable` like bellow:

```typescript
new StackSpotDynamoDBTable(this, 'HelloWorldTable', {
  // other settings...
  generateRepository: true,
}
```

If you'd like to configure some options, add the `repositoryGenerationConfiguration` object, like:

```typescript
new StackSpotDynamoDBTable(this, 'HelloWorldTable', {
  // other settings...
  generateRepository: true,
  repositoryGenerationConfiguration: {
    tracing: false,
    sourceDir: 'src',
  },
}
```

- `tracing` - enable x-ray tracing - _default: true_
- `sourceDir` - change the default source foldes: _default: src_

## Useful commands

- `npm run build` compile typescript to jsii
- `npm run watch` watch for changes and compile
- `npm run test` perform the jest unit tests
- `npm run package` package library using jsii
- `npm run coverage` run tests with coverage reports

## References

### CDK

- <https://docs.aws.amazon.com/cdk/latest/guide/home.html> - CDK Developer guide
- <https://docs.aws.amazon.com/cdk/api/latest/docs/aws-apigateway-readme.html> - CDK Amazon API Gateway Construct Library
- <https://aws.github.io/jsii/user-guides/lib-author/> - jsii library author guide
- <https://cdk-advanced.workshop.aws/> - CDK advanced workshop
- <https://docs.aws.amazon.com/cdk/latest/guide/videos.html> - CDK Videos
- <https://docs.aws.amazon.com/cdk/api/latest/docs/aws-dynamodb-readme.html> - CDK DynamoDB Construct Library
