ag-common 0.0.460 → 0.0.461

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,58 +1,52 @@
1
- import DynamoDB from 'aws-sdk/clients/dynamodb';
1
+ import { DynamoDBDocument } from '@aws-sdk/lib-dynamodb';
2
2
  import { DYNAMOKEYS, IQueryDynamo, Key } from '../types';
3
- export declare let dynamoDb: DynamoDB.DocumentClient;
4
- export declare const setDynamo: (region: string) => void;
5
- export declare const putDynamo: <T>(item: T, tableName: string, opt?: {
3
+ export declare const setDynamo: (region: string) => DynamoDBDocument;
4
+ export declare let dynamoDb: DynamoDBDocument;
5
+ export declare const putDynamo: <T extends Record<string, any>>(item: T, tableName: string, opt?: {
6
6
  /** if provided, will assert this PK value doesnt already exist */
7
7
  pkName?: string;
8
8
  }) => Promise<{
9
- error?: string | undefined;
10
- data?: T | undefined;
9
+ error?: string;
11
10
  }>;
12
- export declare const batchWrite: <T extends {}>(tableName: string, itemsIn: T[], breakOnError?: boolean) => Promise<{
13
- error?: string | undefined;
11
+ export declare const batchWrite: <T extends Record<string, any>>(tableName: string, itemsIn: T[]) => Promise<{
12
+ error?: string;
14
13
  }>;
15
- export declare const batchDelete: ({ tableName, breakOnError, pkName, keys, rangeName, rangeKeys, }: {
16
- pkName: string;
17
- breakOnError?: boolean | undefined;
14
+ export declare const batchDelete: ({ tableName, keys, pkName, }: {
18
15
  tableName: string;
19
16
  keys: string[];
20
- rangeName?: string | undefined;
21
- rangeKeys?: string[] | undefined;
22
- }) => Promise<{
23
- error: string;
24
- } | {
25
- error?: undefined;
26
- }>;
27
- export declare const scan: <T>(tableName: string, opt?: {
28
- filter?: {
29
- filterExpression: string;
30
- attrNames: Record<string, string>;
31
- attrValues: Record<string, string>;
32
- };
33
- /** ProjectionExpression. will csv values */
34
- requiredAttributeList?: string[];
35
- }) => Promise<T[]>;
36
- export declare const getItemDynamo: <T>({ tableName, pkName, pkValue, }: {
37
17
  pkName: string;
38
- pkValue: string;
39
- tableName: string;
40
- }) => Promise<T>;
18
+ }) => Promise<{}>;
19
+ export declare const scan: <T>(tableName: string) => Promise<{
20
+ data?: T[] | undefined;
21
+ error?: string | undefined;
22
+ }>;
41
23
  export declare const getItemsDynamo: <T>({ tableName, items, }: {
42
24
  items: {
43
25
  pkName: string;
44
26
  pkValue: string;
45
27
  }[];
46
28
  tableName: string;
47
- }) => Promise<T[]>;
48
- export declare const queryDynamo: <T>({ tableName, pkName, pkValue, pkOperator, skName, skValue, skOperator, indexName, count, startKey: startKeyIn, filterName, filterValue, filterOperator, sortAscending, }: IQueryDynamo) => Promise<{
49
- Items: T[];
29
+ }) => Promise<{
30
+ data?: T[] | undefined;
31
+ error?: string | undefined;
32
+ }>;
33
+ export declare const getItemDynamo: <T>({ tableName, pkName, pkValue, }: {
34
+ pkName: string;
35
+ pkValue: string;
36
+ tableName: string;
37
+ }) => Promise<{
38
+ data?: T | undefined;
39
+ error?: string | undefined;
40
+ }>;
41
+ export declare const queryDynamo: <T>({ tableName, pkName, pkValue, pkOperator, skName, skValue, skOperator, indexName, count, startKeyPk, filterName, filterValue, filterOperator, sortAscending, }: IQueryDynamo) => Promise<{
42
+ Items?: T[] | undefined;
50
43
  startKey?: Key | undefined;
44
+ error?: string | undefined;
51
45
  }>;
52
46
  export declare const getDynamoTtlDays: (days: number) => number;
53
47
  export declare const getDynamoTtlMinutes: (mins: number) => number;
54
48
  export declare const wipeTable: (tableName: string) => Promise<{
55
- errors?: string[] | undefined;
49
+ errors?: string[];
56
50
  }>;
57
51
  export declare const getDynamoUpdates: (items: DYNAMOKEYS) => {
58
52
  UpdateExpression: string;
@@ -1,27 +1,8 @@
1
1
  "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || function (mod) {
19
- if (mod && mod.__esModule) return mod;
20
- var result = {};
21
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
- __setModuleDefault(result, mod);
23
- return result;
24
- };
2
+ /* eslint-disable guard-for-in */
3
+ /* eslint-disable no-restricted-syntax */
4
+ /* eslint-disable no-await-in-loop */
5
+ /* eslint-disable prefer-const */
25
6
  var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
26
7
  function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
27
8
  return new (P || (P = Promise))(function (resolve, reject) {
@@ -32,53 +13,56 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
32
13
  });
33
14
  };
34
15
  Object.defineProperty(exports, "__esModule", { value: true });
35
- exports.getDynamoUpdates = exports.wipeTable = exports.getDynamoTtlMinutes = exports.getDynamoTtlDays = exports.queryDynamo = exports.getItemsDynamo = exports.getItemDynamo = exports.scan = exports.batchDelete = exports.batchWrite = exports.putDynamo = exports.setDynamo = exports.dynamoDb = void 0;
36
- /* eslint-disable guard-for-in */
37
- /* eslint-disable no-restricted-syntax */
38
- /* eslint-disable no-await-in-loop */
39
- /* eslint-disable prefer-const */
40
- const dynamodb_1 = __importStar(require("aws-sdk/clients/dynamodb"));
16
+ exports.getDynamoUpdates = exports.wipeTable = exports.getDynamoTtlMinutes = exports.getDynamoTtlDays = exports.queryDynamo = exports.getItemDynamo = exports.getItemsDynamo = exports.scan = exports.batchDelete = exports.batchWrite = exports.putDynamo = exports.dynamoDb = exports.setDynamo = void 0;
17
+ const client_dynamodb_1 = require("@aws-sdk/client-dynamodb");
18
+ const lib_dynamodb_1 = require("@aws-sdk/lib-dynamodb");
19
+ // ES6 import
41
20
  const array_1 = require("../../common/helpers/array");
42
21
  const async_1 = require("../../common/helpers/async");
43
22
  const log_1 = require("../../common/helpers/log");
44
23
  const sleep_1 = require("../../common/helpers/sleep");
45
- // eslint-disable-next-line import/no-mutable-exports
46
- exports.dynamoDb = new dynamodb_1.DocumentClient();
47
24
  const setDynamo = (region) => {
48
- exports.dynamoDb = new dynamodb_1.DocumentClient({ region });
25
+ let raw = new client_dynamodb_1.DynamoDBClient({ region });
26
+ const ddbDocClient = lib_dynamodb_1.DynamoDBDocument.from(raw);
27
+ return ddbDocClient;
49
28
  };
50
29
  exports.setDynamo = setDynamo;
30
+ exports.dynamoDb = (0, exports.setDynamo)('ap-southeast-2');
31
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
51
32
  const putDynamo = (item, tableName, opt) => __awaiter(void 0, void 0, void 0, function* () {
52
- const params = Object.assign({ TableName: tableName,
53
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
54
- Item: item }, ((opt === null || opt === void 0 ? void 0 : opt.pkName) && {
33
+ let params = new lib_dynamodb_1.PutCommand(Object.assign({ TableName: tableName, Item: item }, ((opt === null || opt === void 0 ? void 0 : opt.pkName) && {
55
34
  ConditionExpression: `attribute_not_exists(${opt.pkName})`,
56
- }));
57
- (0, log_1.info)(`running dynamo put=${JSON.stringify(params, null, 2)}`);
58
- // write the todo to the database
59
- const put = yield exports.dynamoDb.put(params).promise();
60
- if (put.$response.error && put.$response.error.statusCode) {
61
- return { error: put.$response.error.message };
35
+ })));
36
+ (0, log_1.debug)(`running dynamo put=${JSON.stringify(params, null, 2)}`);
37
+ try {
38
+ let r1 = yield exports.dynamoDb.send(params);
39
+ console.log('r1=', r1);
40
+ return {};
41
+ }
42
+ catch (e) {
43
+ (0, log_1.warn)('put error', e);
44
+ return { error: e.toString() };
62
45
  }
63
- // put never returns into, so just use what we have already
64
- return { data: item };
65
46
  });
66
47
  exports.putDynamo = putDynamo;
67
- let batchWriteRaw = (req) => __awaiter(void 0, void 0, void 0, function* () {
68
- let count = 0;
69
- let max = 5;
70
- // eslint-disable-next-line no-constant-condition
71
- while (true)
48
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
49
+ const batchWrite = (tableName, itemsIn) => __awaiter(void 0, void 0, void 0, function* () {
50
+ //batch up to 20, so we can retry.
51
+ let chunked = (0, array_1.chunk)(itemsIn, 20);
52
+ yield (0, async_1.asyncForEach)(chunked, (items) => __awaiter(void 0, void 0, void 0, function* () {
53
+ let retryCount = 0;
54
+ let retryMax = 3;
55
+ let params = new lib_dynamodb_1.BatchWriteCommand({
56
+ RequestItems: {
57
+ [`${tableName}`]: items.map((Item) => ({
58
+ PutRequest: { Item: Item },
59
+ })),
60
+ },
61
+ });
62
+ (0, log_1.debug)(`running dynamo batchWrite=${JSON.stringify(params, null, 2)}`);
72
63
  try {
73
- const res = yield exports.dynamoDb
74
- .batchWrite({
75
- RequestItems: req,
76
- })
77
- .promise();
78
- if (res.$response.error) {
79
- throw new Error(res.$response.error.message);
80
- }
81
- return res;
64
+ yield exports.dynamoDb.send(params);
65
+ return {};
82
66
  }
83
67
  catch (e) {
84
68
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -87,168 +71,110 @@ let batchWriteRaw = (req) => __awaiter(void 0, void 0, void 0, function* () {
87
71
  (0, log_1.warn)('dynamo write error', msg);
88
72
  if (es.indexOf('429') !== -1 ||
89
73
  es.indexOf('ProvisionedThroughputExceeded') !== -1) {
90
- count += 1;
91
- msg = `batch write throttled. retry ${count}/${max}`;
74
+ retryCount += 1;
75
+ msg = `batch write throttled. retry ${retryCount}/${retryMax}`;
92
76
  }
93
77
  else {
94
78
  throw e;
95
79
  }
96
- if (count >= max) {
80
+ if (retryCount >= retryMax) {
97
81
  throw e;
98
82
  }
99
- (0, log_1.warn)(`dynamo retry ${count}/${max}`);
83
+ (0, log_1.warn)(`dynamo retry ${retryCount}/${retryMax}`);
100
84
  yield (0, sleep_1.sleep)(2000);
101
85
  }
102
- });
103
- // eslint-disable-next-line @typescript-eslint/ban-types
104
- const batchWrite = (tableName, itemsIn, breakOnError = false) => __awaiter(void 0, void 0, void 0, function* () {
105
- var _a, _b;
106
- let items = JSON.parse(JSON.stringify(itemsIn));
107
- (0, log_1.debug)(`push to dynamo:${tableName} - count=${itemsIn.length}`);
108
- const error = [];
109
- while (items.length > 0) {
110
- const { part, rest } = (0, array_1.take)(items, 25);
111
- // eslint-disable-next-line no-param-reassign
112
- items = rest;
113
- let req = {
114
- [`${tableName}`]: part.map((item) => ({
115
- PutRequest: { Item: item },
116
- })),
117
- };
118
- let res = yield batchWriteRaw(req);
119
- const newError = (_b = (_a = res.$response) === null || _a === void 0 ? void 0 : _a.error) !== null && _b !== void 0 ? _b : null;
120
- if (newError) {
121
- error.push(newError);
122
- if (breakOnError) {
123
- items = [];
124
- }
125
- }
126
- }
127
- if ((error === null || error === void 0 ? void 0 : error.length) > 0) {
128
- const me = error.join('\n');
129
- (0, log_1.error)(`batch write error=${me}`);
130
- return { error: me };
131
- }
86
+ }));
132
87
  return {};
133
88
  });
134
89
  exports.batchWrite = batchWrite;
135
- const batchDelete = ({ tableName, breakOnError = true, pkName, keys, rangeName, rangeKeys, }) => __awaiter(void 0, void 0, void 0, function* () {
136
- (0, log_1.info)(`wipe keys dynamo:${tableName} - count=${keys.length}`);
137
- const error = [];
138
- let breakV = false;
139
- yield (0, async_1.asyncForEach)(keys, (key, i) => __awaiter(void 0, void 0, void 0, function* () {
140
- var _c, _d;
141
- if (breakV) {
142
- return;
90
+ const batchDelete = ({ tableName, keys, pkName, }) => __awaiter(void 0, void 0, void 0, function* () {
91
+ //batch up to 20, so we can retry.
92
+ let chunked = (0, array_1.chunk)(keys, 20);
93
+ yield (0, async_1.asyncForEach)(chunked, (items) => __awaiter(void 0, void 0, void 0, function* () {
94
+ let retryCount = 0;
95
+ let retryMax = 3;
96
+ let params = new lib_dynamodb_1.BatchWriteCommand({
97
+ RequestItems: {
98
+ [`${tableName}`]: items.map((key) => ({
99
+ DeleteRequest: { Key: { [`${pkName}`]: key } },
100
+ })),
101
+ },
102
+ });
103
+ (0, log_1.debug)(`running dynamo batch delete=${JSON.stringify(params, null, 2)}`);
104
+ try {
105
+ yield exports.dynamoDb.send(params);
106
+ return {};
143
107
  }
144
- let params = {
145
- TableName: tableName,
146
- Key: { [pkName]: key },
147
- };
148
- if (rangeName) {
149
- let rangeValue = rangeKeys === null || rangeKeys === void 0 ? void 0 : rangeKeys[i];
150
- if (rangeValue) {
151
- params.Key[rangeName] = rangeValue;
108
+ catch (e) {
109
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
110
+ let es = e.toString();
111
+ let msg = es;
112
+ (0, log_1.warn)('dynamo write error', msg);
113
+ if (es.indexOf('429') !== -1 ||
114
+ es.indexOf('ProvisionedThroughputExceeded') !== -1) {
115
+ retryCount += 1;
116
+ msg = `batch delete write throttled. retry ${retryCount}/${retryMax}`;
152
117
  }
153
- }
154
- const res = yield exports.dynamoDb.delete(params).promise();
155
- const newError = (_d = (_c = res.$response) === null || _c === void 0 ? void 0 : _c.error) !== null && _d !== void 0 ? _d : null;
156
- if (newError) {
157
- error.push(newError);
158
- if (breakOnError) {
159
- breakV = true;
118
+ else {
119
+ throw e;
120
+ }
121
+ if (retryCount >= retryMax) {
122
+ throw e;
160
123
  }
124
+ (0, log_1.warn)(`dynamo retry ${retryCount}/${retryMax}`);
125
+ yield (0, sleep_1.sleep)(2000);
161
126
  }
162
127
  }));
163
- if ((error === null || error === void 0 ? void 0 : error.length) > 0) {
164
- const me = error.join('\n');
165
- (0, log_1.error)(`batch write error=${me}`);
166
- return { error: me };
167
- }
168
128
  return {};
169
129
  });
170
130
  exports.batchDelete = batchDelete;
171
- const scan = (tableName, opt) => __awaiter(void 0, void 0, void 0, function* () {
172
- const Items = [];
173
- let ExclusiveStartKey;
174
- do {
175
- let params = {
176
- TableName: tableName,
177
- ExclusiveStartKey,
178
- };
179
- if (opt === null || opt === void 0 ? void 0 : opt.filter) {
180
- params.FilterExpression = opt.filter.filterExpression;
181
- params.ExpressionAttributeNames = opt.filter.attrNames;
182
- params.ExpressionAttributeValues = opt.filter.attrValues;
183
- }
184
- if (opt === null || opt === void 0 ? void 0 : opt.requiredAttributeList) {
185
- params.ProjectionExpression = opt.requiredAttributeList.join(', ');
186
- }
187
- const { Items: newitems, LastEvaluatedKey, $response,
188
- // eslint-disable-next-line no-await-in-loop
189
- } = yield exports.dynamoDb.scan(params).promise();
190
- ExclusiveStartKey = LastEvaluatedKey;
191
- if ($response.error && $response.error.statusCode) {
192
- throw new Error($response.error.message);
193
- }
194
- if (newitems) {
195
- Items.push(...newitems.map((r) => r));
196
- }
197
- } while (ExclusiveStartKey);
198
- (0, log_1.info)(`dynamo scan against ${tableName} ok, count=${Items === null || Items === void 0 ? void 0 : Items.length}`);
199
- return Items;
200
- });
201
- exports.scan = scan;
202
- const getItemDynamo = ({ tableName, pkName, pkValue, }) => __awaiter(void 0, void 0, void 0, function* () {
203
- const params = {
204
- Key: { [pkName]: pkValue },
131
+ const scan = (tableName) => __awaiter(void 0, void 0, void 0, function* () {
132
+ var _a;
133
+ let params = new lib_dynamodb_1.ScanCommand({
205
134
  TableName: tableName,
206
- };
135
+ });
136
+ (0, log_1.debug)(`running dynamo scan=${JSON.stringify(params, null, 2)}`);
207
137
  try {
208
- const res = yield exports.dynamoDb.get(params).promise();
209
- const ret = res.Item;
210
- (0, log_1.debug)(`got dynamo getitem=${JSON.stringify(params, null, 2)}`);
211
- return ret;
138
+ let ret = yield exports.dynamoDb.send(params);
139
+ let items = ((_a = ret.Items) !== null && _a !== void 0 ? _a : []).map((r) => r);
140
+ return { data: items };
212
141
  }
213
142
  catch (e) {
214
- (0, log_1.error)(e);
215
- throw e;
143
+ return { error: e.toString() };
216
144
  }
217
145
  });
218
- exports.getItemDynamo = getItemDynamo;
146
+ exports.scan = scan;
219
147
  const getItemsDynamo = ({ tableName, items, }) => __awaiter(void 0, void 0, void 0, function* () {
220
- var _e, _f;
221
- const params = {
148
+ var _b, _c;
149
+ const params = new lib_dynamodb_1.BatchGetCommand({
222
150
  RequestItems: {
223
151
  [tableName]: {
224
152
  Keys: items.map(({ pkName, pkValue }) => ({
225
- [pkName]: { S: pkValue },
153
+ [pkName]: pkValue,
226
154
  })),
227
155
  },
228
156
  },
229
- };
230
- const dbRaw = new dynamodb_1.default({ apiVersion: '2012-10-08' });
157
+ });
231
158
  try {
232
- const res = yield dbRaw.batchGetItem(params).promise();
233
- (0, log_1.debug)(`got dynamo getitems=${JSON.stringify(res, null, 2)}`);
234
- let ret = ((_f = (_e = res.Responses) === null || _e === void 0 ? void 0 : _e[tableName]) === null || _f === void 0 ? void 0 : _f.map((s) => dynamodb_1.Converter.unmarshall(s))) ||
235
- [];
236
- return ret;
159
+ let res = yield exports.dynamoDb.send(params);
160
+ let data = (_c = (_b = res.Responses) === null || _b === void 0 ? void 0 : _b[tableName].map((r) => r)) !== null && _c !== void 0 ? _c : [];
161
+ return { data };
237
162
  }
238
163
  catch (e) {
239
- let msg = `error with getitems query:` +
240
- JSON.stringify(params, null, 2) +
241
- '\n' +
242
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
243
- e.toString();
244
- (0, log_1.error)(msg);
245
- throw e;
164
+ (0, log_1.warn)('get error:', e);
165
+ return { error: e.toString() };
166
+ //
246
167
  }
247
168
  });
248
169
  exports.getItemsDynamo = getItemsDynamo;
249
- const queryDynamo = ({ tableName, pkName, pkValue, pkOperator = '=', skName, skValue, skOperator = '=', indexName, count = 1000, startKey: startKeyIn, filterName, filterValue, filterOperator = '=', sortAscending = true, }) => __awaiter(void 0, void 0, void 0, function* () {
250
- var _g;
251
- let startKey = startKeyIn;
170
+ const getItemDynamo = ({ tableName, pkName, pkValue, }) => __awaiter(void 0, void 0, void 0, function* () {
171
+ var _d;
172
+ let r = yield (0, exports.getItemsDynamo)({ tableName, items: [{ pkName, pkValue }] });
173
+ return { data: (_d = r.data) === null || _d === void 0 ? void 0 : _d[0], error: r.error };
174
+ });
175
+ exports.getItemDynamo = getItemDynamo;
176
+ const queryDynamo = ({ tableName, pkName, pkValue, pkOperator = '=', skName, skValue, skOperator = '=', indexName, count = 1000, startKeyPk, filterName, filterValue, filterOperator = '=', sortAscending = true, }) => __awaiter(void 0, void 0, void 0, function* () {
177
+ var _e;
252
178
  let kce = `#${pkName.toLowerCase()} ${pkOperator} :${pkName.toLowerCase()}`;
253
179
  const ean = { [`#${pkName.toLowerCase()}`]: pkName };
254
180
  const eav = {
@@ -292,50 +218,32 @@ const queryDynamo = ({ tableName, pkName, pkValue, pkOperator = '=', skName, skV
292
218
  }
293
219
  }
294
220
  const Items = [];
221
+ let startKey = startKeyPk
222
+ ? { [`${pkName}`]: { S: startKeyPk } }
223
+ : undefined;
295
224
  do {
296
- const params = {
297
- TableName: tableName,
298
- KeyConditionExpression: kce,
299
- ExpressionAttributeNames: ean,
300
- ExpressionAttributeValues: eav,
225
+ const params = new lib_dynamodb_1.QueryCommand(Object.assign(Object.assign(Object.assign(Object.assign({ TableName: tableName, KeyConditionExpression: kce, ExpressionAttributeNames: ean, ExpressionAttributeValues: eav }, (startKey && {
301
226
  ExclusiveStartKey: startKey,
302
- FilterExpression,
303
- ScanIndexForward: sortAscending,
304
- };
305
- if (count > 0) {
306
- params.Limit = count;
307
- }
308
- else {
309
- params.Limit = 1000;
310
- }
311
- if (indexName) {
312
- params.IndexName = indexName;
313
- }
314
- let newitems;
227
+ })), (FilterExpression && { FilterExpression })), { ScanIndexForward: sortAscending, Limit: count > 0 ? count : 1000 }), (indexName && { IndexName: indexName })));
315
228
  let lek;
316
- let $response;
229
+ let newItems;
317
230
  try {
318
231
  ({
319
- Items: newitems,
232
+ Items: newItems,
320
233
  LastEvaluatedKey: lek,
321
- $response,
322
234
  // eslint-disable-next-line no-await-in-loop
323
- } = yield exports.dynamoDb.query(params).promise());
235
+ } = yield exports.dynamoDb.send(params));
236
+ if (newItems) {
237
+ Items.push(...newItems.map((i) => i));
238
+ }
324
239
  }
325
240
  catch (e) {
326
- (0, log_1.error)('error. query params=', JSON.stringify(params), e);
327
- throw e;
241
+ (0, log_1.warn)('error. query params=', JSON.stringify(params), e);
242
+ return { error: e.toString() };
328
243
  }
329
244
  startKey = lek;
330
- if ($response.error) {
331
- (0, log_1.error)('error. query params=', JSON.stringify(params));
332
- throw new Error($response.error.message);
333
- }
334
- (0, log_1.debug)(`dynamo query against ${params === null || params === void 0 ? void 0 : params.TableName} ok, count=${newitems === null || newitems === void 0 ? void 0 : newitems.length} ${JSON.stringify(params)}`, ` next startkey=${startKey}`);
335
- if (newitems) {
336
- Items.push(...newitems.map((r) => r));
337
- }
338
- if (count > 0 && ((_g = newitems === null || newitems === void 0 ? void 0 : newitems.length) !== null && _g !== void 0 ? _g : 0) >= count) {
245
+ (0, log_1.debug)(`dynamo query against ${params === null || params === void 0 ? void 0 : params.input.TableName} ok, count=${newItems === null || newItems === void 0 ? void 0 : newItems.length} ${JSON.stringify(params)}`, ` next startkey=${startKey}`);
246
+ if (count > 0 && ((_e = newItems === null || newItems === void 0 ? void 0 : newItems.length) !== null && _e !== void 0 ? _e : 0) >= count) {
339
247
  return { Items, startKey };
340
248
  }
341
249
  } while (startKey && Object.keys(startKey).length > 0);
@@ -347,51 +255,22 @@ exports.getDynamoTtlDays = getDynamoTtlDays;
347
255
  const getDynamoTtlMinutes = (mins) => Math.ceil(new Date().getTime() / 1000) + mins * 60;
348
256
  exports.getDynamoTtlMinutes = getDynamoTtlMinutes;
349
257
  const wipeTable = (tableName) => __awaiter(void 0, void 0, void 0, function* () {
350
- var _h;
351
- const dbRaw = new dynamodb_1.default({ apiVersion: '2012-10-08' });
352
- let infoV = yield dbRaw
353
- .describeTable({
354
- TableName: tableName,
355
- })
356
- .promise();
258
+ var _f, _g;
259
+ let infoV = yield exports.dynamoDb.send(new client_dynamodb_1.DescribeTableCommand({ TableName: tableName }));
357
260
  // eslint-disable-next-line @typescript-eslint/ban-ts-comment
358
261
  // @ts-ignore
359
262
  let keyHash = infoV.Table.KeySchema.find((k) => k.KeyType === 'HASH').AttributeName;
360
- const params = {
361
- TableName: tableName,
362
- ExclusiveStartKey: undefined,
363
- };
364
- let all = [];
365
- let working;
366
- do {
367
- working = yield dbRaw.scan(params).promise();
368
- (_h = working.Items) === null || _h === void 0 ? void 0 : _h.forEach((item) => all.push(item));
369
- params.ExclusiveStartKey = working.LastEvaluatedKey;
370
- } while (typeof working.LastEvaluatedKey !== 'undefined');
371
- (0, log_1.warn)(`will delete ${all === null || all === void 0 ? void 0 : all.length} items from ${tableName}`);
372
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
373
- // @ts-ignore
374
- const datagr = (0, array_1.chunk)(all, 25);
375
- let res = yield Promise.all(datagr.map((group) => dbRaw
376
- .batchWriteItem({
377
- RequestItems: {
378
- [`${tableName}`]: group.map((s) => ({
379
- DeleteRequest: {
380
- Key: {
381
- [`${keyHash}`]: s[keyHash],
382
- },
383
- },
384
- })),
385
- },
386
- })
387
- .promise()));
388
- let errors = res
389
- .map((r) => { var _a, _b; return ((_b = (((_a = r === null || r === void 0 ? void 0 : r.$response) === null || _a === void 0 ? void 0 : _a.error) || {})) === null || _b === void 0 ? void 0 : _b.message) || undefined; })
390
- .filter(array_1.notEmpty);
391
- if (errors.length > 0) {
392
- (0, log_1.error)('errors=', JSON.stringify(errors));
393
- return { errors };
263
+ if (!keyHash) {
264
+ throw new Error('couldnt find keyHash');
394
265
  }
266
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
267
+ let all = ((_g = (_f = (yield (0, exports.scan)(tableName))) === null || _f === void 0 ? void 0 : _f.data) === null || _g === void 0 ? void 0 : _g.map((d) => d)) || [];
268
+ (0, log_1.warn)(`will delete ${all === null || all === void 0 ? void 0 : all.length} items from ${tableName}`);
269
+ yield (0, exports.batchDelete)({
270
+ tableName,
271
+ keys: all.map((s) => s[keyHash]),
272
+ pkName: 'PK',
273
+ });
395
274
  (0, log_1.warn)(`cleared table ${tableName}`);
396
275
  return {};
397
276
  });
@@ -1,3 +1,4 @@
1
+ import { AttributeValue } from '@aws-sdk/client-dynamodb/dist-types/models/models_0';
1
2
  export interface APIGatewayProxyResult {
2
3
  statusCode: number;
3
4
  headers?: {
@@ -30,20 +31,6 @@ export interface APIGatewayEvent {
30
31
  httpMethod: string;
31
32
  };
32
33
  }
33
- interface AttributeValue {
34
- B?: string | undefined;
35
- BS?: string[] | undefined;
36
- BOOL?: boolean | undefined;
37
- L?: AttributeValue[] | undefined;
38
- M?: {
39
- [id: string]: AttributeValue;
40
- } | undefined;
41
- N?: string | undefined;
42
- NS?: string[] | undefined;
43
- NULL?: boolean | undefined;
44
- S?: string | undefined;
45
- SS?: string[] | undefined;
46
- }
47
34
  export interface AppSyncResolverEvent<TArguments, TSource = Record<string, any> | null> {
48
35
  arguments: TArguments;
49
36
  identity?: any;
@@ -100,4 +87,3 @@ export interface DynamoDBStreamEvent {
100
87
  export type Key = {
101
88
  [key: string]: AttributeValue;
102
89
  };
103
- export {};
@@ -1,5 +1,4 @@
1
1
  import { aws_dynamodb as dynamodb, aws_iam as iam, aws_lambda as lambda } from 'aws-cdk-lib';
2
- import { Key } from './aws';
3
2
  export interface DYNAMOKEYS {
4
3
  type: string;
5
4
  L1: string;
@@ -60,7 +59,7 @@ export interface IQueryDynamo {
60
59
  indexName?: string;
61
60
  /** default 1000 */
62
61
  count?: number;
63
- startKey?: Key;
62
+ startKeyPk?: string;
64
63
  filterName?: string;
65
64
  filterValue?: string | number | boolean;
66
65
  /** default, = */
package/package.json CHANGED
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "0.0.460",
2
+ "version": "0.0.461",
3
3
  "name": "ag-common",
4
4
  "main": "./dist/index.js",
5
5
  "types": "./dist/index.d.ts",
@@ -12,11 +12,15 @@
12
12
  "build": "rimraf dist && tsc -p tsconfig.build.json",
13
13
  "lint": "npx eslint --ext .ts,.tsx .",
14
14
  "start": "cross-env BROWSER=none cross-env storybook dev -p 6006",
15
- "build-storybook": "storybook build -o docs --quiet"
15
+ "build-storybook": "storybook build -o docs --quiet",
16
+ "test-run": "ts-node -- src/api/helpers/dynamo.test.ts"
16
17
  },
17
18
  "dependencies": {
19
+ "@aws-sdk/client-dynamodb": "^3.379.1",
20
+ "@aws-sdk/lib-dynamodb": "^3.379.1",
21
+ "@aws-sdk/util-dynamodb": "^3.379.1",
18
22
  "aws-cdk-lib": ">=2",
19
- "aws-sdk": ">=2",
23
+ "aws-sdk": ">=2.1368.0",
20
24
  "axios": ">=1",
21
25
  "constructs": ">=10",
22
26
  "jsonwebtoken": ">=9",
@@ -42,14 +46,17 @@
42
46
  "@storybook/react": "7.1.1",
43
47
  "@storybook/react-webpack5": "7.1.1",
44
48
  "@storybook/theming": "7.1.1",
49
+ "@types/jest": "^29.5.3",
45
50
  "@types/jsonwebtoken": "9.0.2",
46
51
  "@types/node": "20.4.5",
47
52
  "@types/react": "18.2.17",
48
53
  "@types/react-dom": "18.2.7",
49
54
  "cross-env": "7.0.3",
50
55
  "eslint-config-e7npm": "0.0.13",
56
+ "jest": "^29.6.2",
51
57
  "rimraf": "5.0.1",
52
- "storybook": "7.1.1"
58
+ "storybook": "7.1.1",
59
+ "ts-jest": "^29.1.1"
53
60
  },
54
61
  "files": [
55
62
  "dist/**/*",