ag-common 0.0.732 → 0.0.735

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,370 +0,0 @@
1
- "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }
12
- var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {
13
- if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
14
- var g = generator.apply(thisArg, _arguments || []), i, q = [];
15
- return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i;
16
- function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; }
17
- function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } }
18
- function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
19
- function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
20
- function fulfill(value) { resume("next", value); }
21
- function reject(value) { resume("throw", value); }
22
- function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
23
- };
24
- Object.defineProperty(exports, "__esModule", { value: true });
25
- exports.getDynamoUpdates = exports.wipeTable = exports.getDynamoTtlMinutes = exports.getDynamoTtlDays = exports.queryDynamo = exports.getItemDynamo = exports.getItemsDynamo = exports.scan = exports.batchDelete = exports.batchWrite = exports.putDynamo = exports.setDynamo = exports.dynamoDb = void 0;
26
- exports.scanWithGenerator = scanWithGenerator;
27
- const client_dynamodb_1 = require("@aws-sdk/client-dynamodb");
28
- const lib_dynamodb_1 = require("@aws-sdk/lib-dynamodb");
29
- const array_1 = require("../../common/helpers/array");
30
- const async_1 = require("../../common/helpers/async");
31
- const withRetry_1 = require("./withRetry");
32
- const isError = (result) => 'error' in result;
33
- /**
34
- * Sets up the DynamoDB client with the specified region and credentials.
35
- * @param region - AWS region to connect to
36
- * @param credentials - Optional AWS credentials
37
- * @returns Configured DynamoDBDocument client
38
- */
39
- const setDynamo = (region, credentials) => {
40
- const client = new client_dynamodb_1.DynamoDBClient({ region, credentials });
41
- exports.dynamoDb = lib_dynamodb_1.DynamoDBDocument.from(client, {
42
- marshallOptions: { removeUndefinedValues: true },
43
- });
44
- return exports.dynamoDb;
45
- };
46
- exports.setDynamo = setDynamo;
47
- exports.dynamoDb = (0, exports.setDynamo)('ap-southeast-2');
48
- /**
49
- * Puts a single item into a DynamoDB table.
50
- * @param item - The item to put into the table
51
- * @param tableName - Name of the DynamoDB table
52
- * @param opt - Optional parameters including primary key name for conditional put
53
- * @returns Promise resolving to void on success or error message on failure
54
- */
55
- const putDynamo = (item, tableName, opt) => __awaiter(void 0, void 0, void 0, function* () {
56
- const params = new lib_dynamodb_1.PutCommand(Object.assign({ TableName: tableName, Item: item }, ((opt === null || opt === void 0 ? void 0 : opt.pkName) && {
57
- ConditionExpression: `attribute_not_exists(${opt.pkName})`,
58
- })));
59
- try {
60
- yield (0, withRetry_1.withRetry)(() => exports.dynamoDb.send(params), 'putDynamo');
61
- return { data: undefined };
62
- }
63
- catch (e) {
64
- return { error: e.toString() };
65
- }
66
- });
67
- exports.putDynamo = putDynamo;
68
- /**
69
- * Writes multiple items to a DynamoDB table in batches.
70
- * Automatically chunks items into batches of 20 (or specified size) to comply with DynamoDB limits.
71
- * @param tableName - Name of the DynamoDB table
72
- * @param items - Array of items to write
73
- * @param opt - Optional parameters including batch size and retry behavior
74
- * @returns Promise resolving to void on success or error message on failure
75
- */
76
- const batchWrite = (tableName, items, opt) => __awaiter(void 0, void 0, void 0, function* () {
77
- try {
78
- const { batchSize = 20 } = opt !== null && opt !== void 0 ? opt : {};
79
- const chunked = (0, array_1.chunk)(items, batchSize);
80
- yield (0, async_1.asyncForEach)(chunked, (chunk) => __awaiter(void 0, void 0, void 0, function* () {
81
- const params = new lib_dynamodb_1.BatchWriteCommand({
82
- RequestItems: {
83
- [tableName]: chunk.map((Item) => ({ PutRequest: { Item } })),
84
- },
85
- });
86
- yield (0, withRetry_1.withRetry)(() => exports.dynamoDb.send(params), 'batchWrite', {
87
- maxRetries: (opt === null || opt === void 0 ? void 0 : opt.alwaysRetry) ? null : undefined,
88
- });
89
- }));
90
- return { data: undefined };
91
- }
92
- catch (e) {
93
- return { error: e.toString() };
94
- }
95
- });
96
- exports.batchWrite = batchWrite;
97
- /**
98
- * Deletes multiple items from a DynamoDB table in batches.
99
- * Automatically chunks keys into batches of 20 (or specified size) to comply with DynamoDB limits.
100
- * @param params - Parameters including table name, keys to delete, and options
101
- * @returns Promise resolving to void on success or error message on failure
102
- */
103
- const batchDelete = (params) => __awaiter(void 0, void 0, void 0, function* () {
104
- var _a;
105
- try {
106
- const { batchSize = 20, alwaysRetry = false } = (_a = params.opt) !== null && _a !== void 0 ? _a : {};
107
- const chunked = (0, array_1.chunk)(params.keys, batchSize);
108
- yield (0, async_1.asyncForEach)(chunked, (chunk) => __awaiter(void 0, void 0, void 0, function* () {
109
- const command = new lib_dynamodb_1.BatchWriteCommand({
110
- RequestItems: {
111
- [params.tableName]: chunk.map((key) => ({
112
- DeleteRequest: { Key: { [params.pkName]: key } },
113
- })),
114
- },
115
- });
116
- yield (0, withRetry_1.withRetry)(() => exports.dynamoDb.send(command), 'batchDelete', {
117
- maxRetries: alwaysRetry ? null : undefined,
118
- });
119
- }));
120
- return { data: undefined };
121
- }
122
- catch (e) {
123
- return { error: e.toString() };
124
- }
125
- });
126
- exports.batchDelete = batchDelete;
127
- /**
128
- * Scans a DynamoDB table and returns all matching items.
129
- * Handles pagination automatically and supports filtering and projection.
130
- * @param tableName - Name of the DynamoDB table
131
- * @param options - Optional parameters for filtering, projection, and index usage
132
- * @returns Promise resolving to array of items on success or error message on failure
133
- */
134
- const scan = (tableName, options) => __awaiter(void 0, void 0, void 0, function* () {
135
- var _a, _b;
136
- try {
137
- const Items = [];
138
- let ExclusiveStartKey;
139
- const projectionAttrs = (_a = options === null || options === void 0 ? void 0 : options.requiredAttributeList) === null || _a === void 0 ? void 0 : _a.reduce((acc, attr, index) => {
140
- acc[`#proj${index}`] = attr;
141
- return acc;
142
- }, {});
143
- const expressionAttributeNames = Object.assign(Object.assign({}, projectionAttrs), (_b = options === null || options === void 0 ? void 0 : options.filter) === null || _b === void 0 ? void 0 : _b.attrNames);
144
- do {
145
- const params = new lib_dynamodb_1.ScanCommand(Object.assign(Object.assign(Object.assign(Object.assign({ TableName: tableName, IndexName: options === null || options === void 0 ? void 0 : options.indexName }, ((options === null || options === void 0 ? void 0 : options.filter) && Object.assign({ FilterExpression: options.filter.filterExpression }, (options.filter.attrValues && {
146
- ExpressionAttributeValues: options.filter.attrValues,
147
- })))), (Object.keys(expressionAttributeNames).length > 0 && {
148
- ExpressionAttributeNames: expressionAttributeNames,
149
- })), ((options === null || options === void 0 ? void 0 : options.requiredAttributeList) && {
150
- ProjectionExpression: options.requiredAttributeList
151
- .map((_, index) => `#proj${index}`)
152
- .join(', '),
153
- })), { ExclusiveStartKey }));
154
- const result = yield (0, withRetry_1.withRetry)(() => exports.dynamoDb.send(params), 'scan');
155
- if (result.Items) {
156
- Items.push(...result.Items);
157
- }
158
- ExclusiveStartKey = result.LastEvaluatedKey;
159
- } while (ExclusiveStartKey);
160
- return { data: Items };
161
- }
162
- catch (e) {
163
- return { error: e.toString() };
164
- }
165
- });
166
- exports.scan = scan;
167
- /**
168
- * Scans a DynamoDB table and yields items in batches.
169
- * Useful for processing large tables without loading all items into memory.
170
- * @param tableName - Name of the DynamoDB table
171
- * @param options - Optional parameters including batch size, filtering, and projection
172
- * @returns AsyncGenerator yielding batches of items
173
- * @throws Error if the scan operation fails
174
- */
175
- function scanWithGenerator(tableName, options) {
176
- return __asyncGenerator(this, arguments, function* scanWithGenerator_1() {
177
- var _a, _b, _c;
178
- const BATCH_SIZE = (_a = options === null || options === void 0 ? void 0 : options.BATCH_SIZE) !== null && _a !== void 0 ? _a : 100;
179
- let items = [];
180
- let exclusiveStartKey;
181
- try {
182
- const projectionAttrs = (_b = options === null || options === void 0 ? void 0 : options.requiredAttributeList) === null || _b === void 0 ? void 0 : _b.reduce((acc, attr, index) => {
183
- acc[`#proj${index}`] = attr;
184
- return acc;
185
- }, {});
186
- const expressionAttributeNames = Object.assign(Object.assign({}, projectionAttrs), (_c = options === null || options === void 0 ? void 0 : options.filter) === null || _c === void 0 ? void 0 : _c.attrNames);
187
- do {
188
- const params = new lib_dynamodb_1.ScanCommand(Object.assign(Object.assign(Object.assign(Object.assign({ TableName: tableName, IndexName: options === null || options === void 0 ? void 0 : options.indexName, Limit: BATCH_SIZE }, ((options === null || options === void 0 ? void 0 : options.filter) && Object.assign({ FilterExpression: options.filter.filterExpression }, (options.filter.attrValues && {
189
- ExpressionAttributeValues: options.filter.attrValues,
190
- })))), (Object.keys(expressionAttributeNames).length > 0 && {
191
- ExpressionAttributeNames: expressionAttributeNames,
192
- })), ((options === null || options === void 0 ? void 0 : options.requiredAttributeList) && {
193
- ProjectionExpression: options.requiredAttributeList
194
- .map((_, index) => `#proj${index}`)
195
- .join(', '),
196
- })), { ExclusiveStartKey: exclusiveStartKey }));
197
- const result = yield __await((0, withRetry_1.withRetry)(() => exports.dynamoDb.send(params), 'scanWithGenerator'));
198
- if (result.Items) {
199
- items.push(...result.Items);
200
- // Process items in chunks of BATCH_SIZE
201
- while (items.length >= BATCH_SIZE) {
202
- const batch = items.slice(0, BATCH_SIZE);
203
- items = items.slice(BATCH_SIZE);
204
- yield yield __await(batch);
205
- }
206
- }
207
- exclusiveStartKey = result.LastEvaluatedKey;
208
- } while (exclusiveStartKey);
209
- // Yield any remaining items
210
- if (items.length > 0) {
211
- yield yield __await(items);
212
- }
213
- }
214
- catch (e) {
215
- throw new Error(`Scan generator error: ${e.toString()}`);
216
- }
217
- });
218
- }
219
- const getItemsDynamo = (params) => __awaiter(void 0, void 0, void 0, function* () {
220
- var _a, _b;
221
- try {
222
- const command = new lib_dynamodb_1.BatchGetCommand({
223
- RequestItems: {
224
- [params.tableName]: {
225
- Keys: params.items.map(({ pkName, pkValue }) => ({
226
- [pkName]: pkValue,
227
- })),
228
- },
229
- },
230
- });
231
- const result = yield (0, withRetry_1.withRetry)(() => exports.dynamoDb.send(command), 'getItemsDynamo');
232
- return {
233
- data: (_b = (_a = result.Responses) === null || _a === void 0 ? void 0 : _a[params.tableName]) !== null && _b !== void 0 ? _b : [],
234
- };
235
- }
236
- catch (e) {
237
- return { error: e.toString() };
238
- }
239
- });
240
- exports.getItemsDynamo = getItemsDynamo;
241
- const getItemDynamo = (params) => __awaiter(void 0, void 0, void 0, function* () {
242
- const result = yield (0, exports.getItemsDynamo)({
243
- tableName: params.tableName,
244
- items: [{ pkName: params.pkName, pkValue: params.pkValue }],
245
- });
246
- if (isError(result)) {
247
- return result;
248
- }
249
- return { data: result.data[0] };
250
- });
251
- exports.getItemDynamo = getItemDynamo;
252
- const queryDynamo = (params) => __awaiter(void 0, void 0, void 0, function* () {
253
- var _a, _b, _c;
254
- try {
255
- let kce = `#${params.pkName.toLowerCase()} ${(_a = params.pkOperator) !== null && _a !== void 0 ? _a : '='} :${params.pkName.toLowerCase()}`;
256
- const ean = {
257
- [`#${params.pkName.toLowerCase()}`]: params.pkName,
258
- };
259
- const eav = {
260
- [`:${params.pkName.toLowerCase()}`]: params.pkValue,
261
- };
262
- if (params.skName && params.skValue !== undefined) {
263
- const { skName, skValue, skOperator = '=' } = params;
264
- if (skOperator === 'BETWEEN' && Array.isArray(skValue)) {
265
- const [start, end] = skValue;
266
- kce += ` AND #${skName.toLowerCase()} BETWEEN :${skName}1 AND :${skName}2`;
267
- ean[`#${skName.toLowerCase()}`] = skName;
268
- eav[`:${skName}1`] = start;
269
- eav[`:${skName}2`] = end;
270
- }
271
- else if (skOperator === 'BEGINS_WITH') {
272
- kce += ` AND begins_with(#${skName.toLowerCase()}, :${skName.toLowerCase()})`;
273
- ean[`#${skName.toLowerCase()}`] = skName;
274
- eav[`:${skName.toLowerCase()}`] = skValue;
275
- }
276
- else {
277
- kce += ` AND #${skName.toLowerCase()} ${skOperator} :${skName.toLowerCase()}`;
278
- ean[`#${skName.toLowerCase()}`] = skName;
279
- eav[`:${skName.toLowerCase()}`] = skValue;
280
- }
281
- }
282
- let FilterExpression;
283
- if (params.filterName && params.filterValue !== undefined) {
284
- ean[`#${params.filterName.toLowerCase()}`] = params.filterName;
285
- eav[`:${params.filterName.toLowerCase()}`] = params.filterValue;
286
- FilterExpression =
287
- params.filterOperator === 'contains'
288
- ? `contains(#${params.filterName.toLowerCase()}, :${params.filterName.toLowerCase()})`
289
- : `#${params.filterName.toLowerCase()} ${(_b = params.filterOperator) !== null && _b !== void 0 ? _b : '='} :${params.filterName.toLowerCase()}`;
290
- }
291
- const items = [];
292
- let { startKey } = params;
293
- do {
294
- const queryParams = new lib_dynamodb_1.QueryCommand({
295
- TableName: params.tableName,
296
- KeyConditionExpression: kce,
297
- ExpressionAttributeNames: ean,
298
- ExpressionAttributeValues: eav,
299
- ScanIndexForward: (_c = params.sortAscending) !== null && _c !== void 0 ? _c : true,
300
- Limit: params.limit,
301
- IndexName: params.indexName,
302
- ExclusiveStartKey: startKey,
303
- FilterExpression,
304
- });
305
- const result = yield (0, withRetry_1.withRetry)(() => exports.dynamoDb.send(queryParams), 'queryDynamo');
306
- if (result.Items) {
307
- items.push(...result.Items);
308
- }
309
- startKey = result.LastEvaluatedKey;
310
- if (params.limit && items.length >= params.limit) {
311
- return {
312
- data: items.slice(0, params.limit),
313
- startKey,
314
- };
315
- }
316
- } while (startKey && Object.keys(startKey).length > 0);
317
- return { data: items };
318
- }
319
- catch (e) {
320
- return { error: e.toString() };
321
- }
322
- });
323
- exports.queryDynamo = queryDynamo;
324
- const getDynamoTtlDays = (days) => Math.ceil(Date.now() / 1000) + days * 86400;
325
- exports.getDynamoTtlDays = getDynamoTtlDays;
326
- const getDynamoTtlMinutes = (minutes) => Math.ceil(Date.now() / 1000) + minutes * 60;
327
- exports.getDynamoTtlMinutes = getDynamoTtlMinutes;
328
- const wipeTable = (tableName) => __awaiter(void 0, void 0, void 0, function* () {
329
- var _a, _b, _c;
330
- try {
331
- const info = yield (0, withRetry_1.withRetry)(() => exports.dynamoDb.send(new client_dynamodb_1.DescribeTableCommand({ TableName: tableName })), 'wipeTable-describe');
332
- const keyHash = (_c = (_b = (_a = info.Table) === null || _a === void 0 ? void 0 : _a.KeySchema) === null || _b === void 0 ? void 0 : _b.find((k) => k.KeyType === 'HASH')) === null || _c === void 0 ? void 0 : _c.AttributeName;
333
- if (!keyHash) {
334
- throw new Error('Could not find hash key');
335
- }
336
- const scanResult = yield (0, exports.scan)(tableName);
337
- if (isError(scanResult)) {
338
- throw new Error(scanResult.error);
339
- }
340
- yield (0, exports.batchDelete)({
341
- tableName,
342
- keys: scanResult.data.map((item) => item[keyHash]),
343
- pkName: keyHash,
344
- });
345
- return { data: undefined };
346
- }
347
- catch (e) {
348
- return { error: e.toString() };
349
- }
350
- });
351
- exports.wipeTable = wipeTable;
352
- const getDynamoUpdates = (item, options) => {
353
- var _a;
354
- const excludeKeys = ((_a = options === null || options === void 0 ? void 0 : options.excludeKeys) !== null && _a !== void 0 ? _a : ['PK']).map((k) => k.toLowerCase());
355
- const validEntries = Object.entries(item).filter(([key, value]) => !excludeKeys.includes(key.toLowerCase()) && value != null);
356
- const ExpressionAttributeNames = {};
357
- const ExpressionAttributeValues = {};
358
- const UpdateExpression = validEntries.reduce((expr, [key, value], index) => {
359
- ExpressionAttributeNames[`#${key}`] = key;
360
- ExpressionAttributeValues[`:${key}`] = value;
361
- return `${expr}${index > 0 ? ', ' : ''}#${key} = :${key}`;
362
- }, 'SET ');
363
- return {
364
- UpdateExpression,
365
- ExpressionAttributeNames,
366
- ExpressionAttributeValues,
367
- ReturnValues: 'UPDATED_NEW',
368
- };
369
- };
370
- exports.getDynamoUpdates = getDynamoUpdates;