-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
203 lines (189 loc) · 9.2 KB
/
index.js
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
'use strict';
function initWrapper(fn) {
return async function(...args) {
try {
return await fn.apply(this, args);
} catch (err) {
if (err.code != 'ResourceNotFoundException') throw err;
await this.init(this.schema);
return await fn.apply(this, args);
}
};
}
module.exports = ({AWS = require('aws-sdk'), waitForActive = 180000} = {}) => {
const db = new AWS.DynamoDB();
const client = new AWS.DynamoDB.DocumentClient();
const tables = new Map();
return new Proxy(function() {}, {
get(target, TableName) {
return (
tables.get(TableName) ||
(() => {
const table = new Function(`return class ${TableName} {}`)();
table.define = function(schema) {
this.schema = schema;
};
table.init = async function(schema) {
if (!schema) throw new Error(`Missing schema definition for ${this.name}`);
this.schema = schema;
await db
.createTable({
TableName,
...Object.entries(schema.attributes).reduce(
(
{AttributeDefinitions = [], KeySchema = []},
[AttributeName, {type: AttributeType, range}]
) => ({
AttributeDefinitions: [...AttributeDefinitions, {AttributeName, AttributeType}],
KeySchema: [...KeySchema, {AttributeName, KeyType: range ? 'RANGE' : 'HASH'}],
}),
{}
),
BillingMode: schema.throughput ? 'PROVISIONED' : 'PAY_PER_REQUEST',
ProvisionedThroughput: schema.throughput && {
ReadCapacityUnits:
typeof schema.throughput == 'number'
? schema.throughput
: schema.throughput.read,
WriteCapacityUnits:
typeof schema.throughput == 'number'
? schema.throughput
: schema.throughput.write,
},
SSESpecification: schema.kms && {
Enabled: true,
SSEType: 'KMS',
KMSMasterKeyId: schema.kms,
},
})
.promise();
for (
const start = Date.now();
waitForActive < 0 || Date.now() - start < waitForActive;
await new Promise(resolve => setTimeout(resolve, 500))
) {
const {Table = {}} = await db.describeTable({TableName}).promise();
if (Table.TableStatus == 'ACTIVE') return true;
}
return false;
};
table.scan = initWrapper(async function(opt = {}) {
const {Items} = await client.scan({...opt, TableName}).promise();
return Items;
});
table.get = initWrapper(async function(
Key,
{
attribute: AttributesToGet,
consistent: ConsistentRead,
attributeNames: ExpressionAttributeNames,
projection: ProjectionExpression,
capacity: ReturnConsumedCapacity,
} = {}
) {
const {Item} = await client
.get({
TableName,
Key,
AttributesToGet,
ConsistentRead,
ExpressionAttributeNames,
ProjectionExpression,
ReturnConsumedCapacity,
})
.promise();
return Item || null;
});
table.put = initWrapper(async function(Item, {returns: ReturnValues} = {}) {
const {Attributes} = await client
.put({
TableName,
Item,
ReturnValues,
ReturnConsumedCapacity: 'NONE',
ReturnItemCollectionMetrics: 'NONE',
})
.promise();
return Attributes;
});
table.update = initWrapper(async function(
Key,
{$unset = {}, $push = {}, $pop = {}, ...data},
{returns: ReturnValues} = {}
) {
const {Attributes} = await client
.update({
TableName,
Key,
AttributeUpdates: {
...Object.entries(data).reduce(
(AttributeUpdates, [key, Value]) => ({
...AttributeUpdates,
[key]: {Action: 'PUT', Value},
}),
{}
),
...Object.entries($push).reduce(
(AttributeUpdates, [key, Value]) => ({
...AttributeUpdates,
[key]: {Action: 'ADD', Value},
}),
{}
),
...Object.entries($pop).reduce(
(AttributeUpdates, [key, Value]) => ({
...AttributeUpdates,
[key]: {Action: 'DELETE', Value},
}),
{}
),
...Object.keys($unset).reduce(
(AttributeUpdates, key) => ({
...AttributeUpdates,
[key]: {Action: 'DELETE'},
}),
{}
),
},
ReturnValues,
ReturnConsumedCapacity: 'NONE',
ReturnItemCollectionMetrics: 'NONE',
})
.promise();
return Attributes;
});
table.delete = initWrapper(async function(Item, {returns: ReturnValues} = {}) {
const {Attributes} = await client
.delete({
TableName,
Item,
ReturnValues,
ReturnConsumedCapacity: 'NONE',
ReturnItemCollectionMetrics: 'NONE',
})
.promise();
return Attributes;
});
table.destroy = async function({wait = 0} = {}) {
try {
await db.deleteTable({TableName}).promise();
for (
const start = Date.now();
wait < 0 || Date.now() - start < wait;
await new Promise(resolve => setTimeout(resolve, 500))
) {
await db.describeTable({TableName}).promise();
}
return false;
} catch (err) {
if (err.code == 'ResourceNotFoundException') return true;
throw err;
}
};
tables.set(TableName, table);
return table;
})()
);
},
});
};