Creating Tables with DynamoDB Toolbox

I'm playing around with DynamoDB Toolbox, and one thing that wasn't clear in my mind was how do I actually create a table using the definitions I made using Toolbox.

Quick GitHub issues search lead me to this issue:

How do we create the actual table in aws dynamodb? · Issue #101 · jeremydaly/dynamodb-toolbox
Preference is to not have two definitions for the same table: So how can we either create a table through the api or/and generate a cloudformation template? If this is out of the scope of this libr...

where Simlu was asking the same question, and the answer was "Do It Yourself".

I dread code duplication especially around things like table definitions - it's trivial to have all your tests pass, but in the end, the app fails in production because you have a mismatch between two definitions of the same thing.

I've made a little example repo and a helper. For now, feel free to just copy and paste it.

A helper like this might get into the dynamodb-toolbox itself, so I didn't create a package for it yet. But if jeremydaly decides this code should live in a package, I will do that.

import type { DynamoDB } from "aws-sdk";

type DynamoDBTypes = "string" | "number" | "binary";

type ToolboxData = {
  partitionKey: string;
  sortKey?: string;
  attributes: {
    [key: string]: DynamoDBTypes;
  };
  name: string;
};

function getAttributes(tableDefinition: DynamoDB.CreateTableInput) {
  const typesMap: { [key: string]: DynamoDBTypes } = {
    S: "string",
    N: "number",
    B: "binary",
  };

  return tableDefinition.AttributeDefinitions.reduce((previous, current) => {
    return {
      ...previous,
      [current.AttributeName]: typesMap[current.AttributeType],
    };
  }, {});
}

function getPartitionKey(tableDefinition: DynamoDB.CreateTableInput) {
  return tableDefinition.KeySchema.find((k) => {
    return k.KeyType.toUpperCase() === "HASH";
  }).AttributeName;
}

function getSortKey(tableDefinition: DynamoDB.CreateTableInput) {
  const rangeAttribute = tableDefinition.KeySchema.find((k) => {
    return k.KeyType.toUpperCase() === "RANGE";
  });
  return rangeAttribute ? rangeAttribute.AttributeName : undefined;
}

export const dynamoSdkToToolbox = (
  tableDefinition: DynamoDB.CreateTableInput
): ToolboxData => ({
  partitionKey: getPartitionKey(tableDefinition),
  attributes: getAttributes(tableDefinition),
  sortKey: getSortKey(tableDefinition),
  name: tableDefinition.TableName,
});

(there are tests for it in the example repo)

xolvio/dynamodb-toolbox-examples
Contribute to xolvio/dynamodb-toolbox-examples development by creating an account on GitHub.

This is how to use it. Assuming you have a table definition using AWS SDK format:

import type { DynamoDB } from "aws-sdk";

export const tableDefinition: DynamoDB.CreateTableInput = {
  TableName: "my-table",
  AttributeDefinitions: [
    {
      AttributeType: "S",
      AttributeName: "pk",
    },
    {
      AttributeType: "S",
      AttributeName: "sk",
    },
  ],
  KeySchema: [
    {
      AttributeName: "pk",
      KeyType: "HASH",
    },
    {
      AttributeName: "sk",
      KeyType: "RANGE",
    },
  ],
  BillingMode: "PAY_PER_REQUEST"
};
src/tableDefinition.ts

pass it to the dynamoSdkToToolbox helper:

const DocumentClient = new DynamoDB.DocumentClient()

const MyTable = new Table({
  ...dynamoSdkToToolbox(tableDefinition),
  DocumentClient
})
src/Customer.ts

This will set things like attributes, partitionKey, sortKey, and name for you - making sure they are and stay in sync.

Using the same table definition you can create a table (although you would probably use cloud formation or CDK for that, that's a topic for a separate article, but you might want to use a helper like this to transform the SDK definition to CDK https://gist.github.com/lgandecki/e7806462ce7c3d0d47ce65d44c5aa43d )

await dynamoDB.createTable(tableDefinition).promise()
src/index.ts

Feel free to play around with the code:

xolvio/dynamodb-toolbox-examples
Contribute to xolvio/dynamodb-toolbox-examples development by creating an account on GitHub.

Let me know if you have any questions or thoughts in the comments below.


Let us help you on your journey to Quality Faster

We at Xolv.io specialize in helping our clients get more for less. We can get you to the holy grail of continuous deployment where every commit can go to production — and yes, even for large enterprises.

Feel free to schedule a call or send us a message below to see how we can help.

User icon
Envelope icon

or

Schedule a 30m call
  • For loops in JavaScript (vs _.times)

    From time to time I still see a for loop in JavaScript codebases. Linters are frequently angry about them. Let's see how we can replace them.

  • Sharing scalars between modules with Chimp

    Simplify your Chimp-based project even further with a new @predefined Scalar directive.

  • Adding TypeScript to the official Apollo Platform Tutorial app

    In todays video I go through a preparation of the official Apollo Platform Tutorial App for adding Chimp to it. I decided to divide that task into two steps - first is adding TypeScript to the codebase. Watch me work, struggle, fly through code, hopefully you will learn some tricks :)