-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcreateTable.ts
More file actions
96 lines (92 loc) · 2.78 KB
/
createTable.ts
File metadata and controls
96 lines (92 loc) · 2.78 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
import {
AttributeDefinition,
CreateTableCommand,
DescribeTableCommand,
GlobalSecondaryIndex,
KeySchemaElement,
ProjectionType,
} from "@aws-sdk/client-dynamodb";
import { DynamoObject, getMeta, sharedDynamoClient } from "./dynamoObject";
export async function createTable<T extends DynamoObject<T>>(
DynamoClass: new () => T
) {
const {
partitionKey: partitionKeyName,
sortKey: sortKeyName,
tableName: TableName,
indexes = {},
} = getMeta(DynamoClass);
const KeySchema: KeySchemaElement[] = [
{ AttributeName: partitionKeyName as string, KeyType: "HASH" },
];
const AttributeDefinitions: AttributeDefinition[] = [
{
AttributeName: partitionKeyName as string,
AttributeType: "S", /// only S type keys supported for now.
},
];
if (sortKeyName) {
KeySchema.push({ AttributeName: sortKeyName as string, KeyType: "RANGE" });
AttributeDefinitions.push({
AttributeName: sortKeyName as string,
AttributeType: "S", /// only S type keys supported for now.
});
}
const idx: GlobalSecondaryIndex[] = [];
for (const indexName of Object.keys(indexes)) {
const { partitionKey, sortKey } = indexes[indexName];
const KeySchema: KeySchemaElement[] = [
{ AttributeName: partitionKey as string, KeyType: "HASH" },
];
if (
!AttributeDefinitions.map((attr) => attr.AttributeName).includes(
partitionKey as string
)
) {
AttributeDefinitions.push({
AttributeName: partitionKey as string,
AttributeType: "S", /// only S type keys supported for now.
});
}
if (sortKey) {
KeySchema.push({ AttributeName: sortKey as string, KeyType: "RANGE" });
if (
!AttributeDefinitions.map((attr) => attr.AttributeName).includes(
sortKey as string
)
) {
AttributeDefinitions.push({
AttributeName: sortKey as string,
AttributeType: "S", /// only S type keys supported for now.
});
}
}
idx.push({
KeySchema,
IndexName: indexName,
Projection: { ProjectionType: ProjectionType.ALL },
});
}
return sharedDynamoClient.get().send(
new CreateTableCommand({
TableName,
KeySchema,
GlobalSecondaryIndexes: idx.length ? idx : undefined, /// Only global indexes supported for now
AttributeDefinitions,
BillingMode: "PAY_PER_REQUEST",
})
);
}
export async function ensureTable<T extends DynamoObject<T>>(
DynamoClass: new () => T
) {
const { tableName } = getMeta(DynamoClass);
try {
const result = await sharedDynamoClient
.get()
.send(new DescribeTableCommand({ TableName: tableName }));
if (result.Table?.TableName !== tableName) throw new Error("wrong name");
} catch (error: any) {
await createTable(DynamoClass);
}
}