-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdynamodb-dataloader.ts
215 lines (187 loc) · 7.21 KB
/
dynamodb-dataloader.ts
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
204
205
206
207
208
209
210
211
212
213
214
215
import * as dynamodb from '@aws-sdk/client-dynamodb';
import * as dynamodbLib from '@aws-sdk/lib-dynamodb';
import * as dynamodbUtil from '@aws-sdk/util-dynamodb';
import DataLoader from 'dataloader';
export interface GetRequest {
TableName: string;
Key: Record<string, dynamodbUtil.NativeScalarAttributeValue>;
}
export type ScanRequest = Pick<dynamodbLib.ScanCommandInput,
| 'ConsistentRead'
| 'ExpressionAttributeNames'
| 'ExpressionAttributeValues'
| 'FilterExpression'
| 'IndexName'
| 'Limit'
| 'ProjectionExpression'
| 'ReturnConsumedCapacity'
| 'Segment'
| 'Select'
| 'TableName'
| 'TotalSegments'
>;
export type QueryRequest = Pick<dynamodbLib.QueryCommandInput,
| 'ConsistentRead'
| 'ExpressionAttributeNames'
| 'ExpressionAttributeValues'
| 'FilterExpression'
| 'IndexName'
| 'KeyConditionExpression'
| 'Limit'
| 'ProjectionExpression'
| 'ReturnConsumedCapacity'
| 'ScanIndexForward'
| 'Select'
| 'TableName'
>;
export interface TableSchema {
readonly tableName: string;
readonly keyAttributeNames: readonly [string] | readonly [string, string];
}
export class DynamodbDataLoader {
dynamodbClient: dynamodb.DynamoDBClient;
dynamodbDocumentClient: dynamodbLib.DynamoDBDocumentClient;
scanner = new DataLoader<ScanRequest, Record<string, unknown>[], string>(scanRequests =>
Promise.all(scanRequests.map(async scanRequest => {
const iter = dynamodbLib.paginateScan({
client: this.dynamodbDocumentClient,
}, scanRequest);
const items = [];
for await (const page of iter) {
if (page.Items) items.push(...page.Items);
}
if (this.tableSchemas && (!scanRequest.Select || scanRequest.Select === dynamodb.Select.ALL_ATTRIBUTES)) {
const tableSchema = this.tableSchemas.find(s => s.tableName === scanRequest.TableName);
if (!tableSchema) {
console.warn(`DynamoDB Dataloader: Could not find table schema of table ${scanRequest.TableName}`);
return items;
}
for (const item of items) {
const key = tableSchema.keyAttributeNames.reduce((key, attrName) => ({
...key,
[attrName]: item[attrName],
}), {});
if (Object.values(key).includes(undefined) || Object.values(key).includes(null)) continue;
this.getter.prime({
TableName: scanRequest.TableName ?? '',
Key: key,
}, item);
}
}
return items;
})),
{
cacheKeyFn(key) {
return JSON.stringify({
ExpressionAttributeNames: key.ExpressionAttributeNames,
ExpressionAttributeValues: key.ExpressionAttributeValues,
FilterExpression: key.FilterExpression,
Limit: key.Limit,
ProjectionExpression: key.ProjectionExpression,
Select: key.Select,
TableName: key.TableName,
});
},
},
);
querier = new DataLoader<QueryRequest, Record<string, unknown>[], string>(queryRequests =>
Promise.all(queryRequests.map(async queryRequest => {
const iter = dynamodbLib.paginateQuery({
client: this.dynamodbDocumentClient,
}, queryRequest);
const items = [];
for await (const page of iter) {
if (page.Items) items.push(...page.Items);
}
if (this.tableSchemas && (!queryRequest.Select || queryRequest.Select === dynamodb.Select.ALL_ATTRIBUTES)) {
const tableSchema = this.tableSchemas.find(s => s.tableName === queryRequest.TableName);
if (!tableSchema) {
console.warn(`DynamoDB Dataloader: Could not find table schema of table ${queryRequest.TableName}`);
return items;
}
for (const item of items) {
const key = tableSchema.keyAttributeNames.reduce((key, attrName) => ({
...key,
[attrName]: item[attrName],
}), {});
if (Object.values(key).includes(undefined) || Object.values(key).includes(null)) continue;
this.getter.prime({
TableName: queryRequest.TableName ?? '',
Key: key,
}, item);
}
}
return items;
})),
{
cacheKeyFn(key) {
return JSON.stringify({
ExpressionAttributeNames: key.ExpressionAttributeNames,
ExpressionAttributeValues: key.ExpressionAttributeValues,
FilterExpression: key.FilterExpression,
KeyConditionExpression: key.KeyConditionExpression,
Limit: key.Limit,
ProjectionExpression: key.ProjectionExpression,
Select: key.Select,
TableName: key.TableName,
});
},
},
);
getter = new DataLoader<GetRequest, unknown, string>(
async (getRequests) => {
const byTableName = Object.groupBy(getRequests, req => req.TableName);
let requestItems: dynamodb.BatchGetItemCommandInput['RequestItems'] = Object.fromEntries(Object.entries(byTableName).flatMap(([tableName, reqs]) => {
if (!reqs) return [];
return [[tableName, {
Keys: reqs.map(req => dynamodbUtil.marshall(req.Key)),
ConsistentRead: this.options?.getOptions?.ConsistentRead,
ExpressionAttributeNames: this.options?.getOptions?.ExpressionAttributeNames,
ProjectionExpression: this.options?.getOptions?.ProjectionExpression,
}]];
}));
let responses: Record<string, Record<string, dynamodb.AttributeValue>[]> = {};
while (requestItems && Object.values(requestItems).flat().length) {
const result: dynamodb.BatchGetItemCommandOutput = await this.dynamodbClient.send(new dynamodb.BatchGetItemCommand({
RequestItems: requestItems,
ReturnConsumedCapacity: this.options?.getOptions?.ReturnConsumedCapacity,
}));
responses = {
...responses,
...result.Responses,
};
requestItems = result.UnprocessedKeys;
}
const items = getRequests.map(getRequest =>
responses[getRequest.TableName]?.find(item =>
Object.entries(getRequest.Key).every(([attr, expected]) => {
const a = item[attr];
const b = dynamodbUtil.convertToAttr(expected);
if (a === b) return true;
if (a?.S) return a.S === b.S;
if (a?.N) return a.N === b.N;
if (a?.B) {
if (!b.B) return false;
return Buffer.from(a.B).equals(Buffer.from(b.B));
}
throw new Error(`Unexpected key: ${JSON.stringify(a)}`);
}),
),
);
return items.map(item => item ? dynamodbUtil.unmarshall(item) : item);
},
{
maxBatchSize: 100,
cacheKeyFn: ({ TableName, Key }) => {
return TableName + '|' + Object.keys(Key).sort().map(k => k + ':' + Key[k]).join('|');
},
},
);
constructor(readonly tableSchemas?: readonly TableSchema[], readonly options?: {
readonly dynamodbClient?: dynamodb.DynamoDBClient;
readonly getOptions?: Pick<dynamodb.KeysAndAttributes, 'ConsistentRead' | 'ProjectionExpression' | 'ExpressionAttributeNames'> & Pick<dynamodb.BatchGetItemCommandInput, 'ReturnConsumedCapacity'>;
}) {
this.dynamodbClient = options?.dynamodbClient ?? new dynamodb.DynamoDBClient({});
this.dynamodbDocumentClient = dynamodbLib.DynamoDBDocumentClient.from(this.dynamodbClient);
}
}