in packages/aws-rfdk/lib/lambdas/nodejs/lib/dynamodb/composite-table.ts [41:88]
public static async fromExisting(client: DynamoDBClient, tableName: string): Promise<CompositeStringIndexTable> {
// Determine the key schema of the table
// We let this throw if the table does not exist.
// See: https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB.html#describeTable-property
const describeResponse = await client.send(new DescribeTableCommand({ TableName: tableName }));
if (!describeResponse.Table) {
throw Error(`Could not describeTable for Table '${tableName}'`);
}
const keySchema = describeResponse.Table.KeySchema;
if (!keySchema) {
throw Error(`Could not get KeySchema for Table '${tableName}'`);
}
const attributes = describeResponse.Table.AttributeDefinitions;
if (!attributes) {
throw Error(`Could not get Attributes for Table '${tableName}'`);
}
// Find the names of the Primary & Sort keys.
const hashIndex: number = keySchema.findIndex(item => item.KeyType === 'HASH');
const sortIndex: number = keySchema.findIndex(item => item.KeyType === 'RANGE');
if (hashIndex < 0 || sortIndex < 0) {
console.debug(`Error initializing DynamoDatabase. KeySchema: ${JSON.stringify(keySchema)}`);
if (hashIndex < 0) {
throw Error(`Could not find PrimaryKey of Table '${tableName}'`);
} else {
throw Error(`Could not find SortKey of Table '${tableName}'`);
}
}
const primaryKey = keySchema[hashIndex].AttributeName;
const sortKey = keySchema[sortIndex].AttributeName;
// Make sure that the primary & sort key types are both string types
// (( We didn't make this flexible enough for other attribute types for the key ))
if ('S' !== attributes.find(item => item.AttributeName === primaryKey)?.AttributeType) {
throw Error(`Primary key '${primaryKey}' must be string type`);
}
if ('S' !== attributes.find(item => item.AttributeName === sortKey)?.AttributeType) {
throw Error(`Sort key '${sortKey}' must be string type`);
}
return new CompositeStringIndexTable(
client,
tableName,
primaryKey!,
sortKey!,
);
}