@qrvey/data-persistence 0.5.8 → 0.5.9-bundled

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.
Files changed (29) hide show
  1. package/dist/cjs/index.js +3 -1
  2. package/dist/cjs/index.js.map +1 -1
  3. package/dist/cjs/services/crud.service.js +2 -2
  4. package/dist/cjs/services/crud.service.js.map +1 -1
  5. package/dist/cjs/services/crudFactory.service.js +5 -44
  6. package/dist/cjs/services/crudFactory.service.js.map +1 -1
  7. package/dist/cjs/services/cruds/dynamodb/dynamoDbCrud.service.js +6 -7
  8. package/dist/cjs/services/cruds/dynamodb/dynamoDbCrud.service.js.map +1 -1
  9. package/dist/cjs/services/cruds/index.js +19 -0
  10. package/dist/cjs/services/cruds/index.js.map +1 -0
  11. package/dist/cjs/services/cruds/postgresql/postgreSqlClient.service.js +21 -21
  12. package/dist/cjs/services/cruds/postgresql/postgreSqlClient.service.js.map +1 -1
  13. package/dist/cjs/services/cruds/postgresql/postgreSqlCrud.service.js +4 -2
  14. package/dist/cjs/services/cruds/postgresql/postgreSqlCrud.service.js.map +1 -1
  15. package/dist/cjs/services/cruds/postgresql/query.service.js +2 -2
  16. package/dist/cjs/services/cruds/postgresql/query.service.js.map +1 -1
  17. package/dist/esm/index.d.mts +3 -2
  18. package/dist/esm/index.mjs +1799 -14
  19. package/dist/esm/index.mjs.map +1 -1
  20. package/dist/types/index.d.ts +3 -2
  21. package/package.json +5 -19
  22. package/dist/esm/chunk-2H6RO6ZL.mjs +0 -56
  23. package/dist/esm/chunk-2H6RO6ZL.mjs.map +0 -1
  24. package/dist/esm/chunk-2OYWEFNZ.mjs +0 -105
  25. package/dist/esm/chunk-2OYWEFNZ.mjs.map +0 -1
  26. package/dist/esm/dynamoDbCrud.service-NRSGRPDQ.mjs +0 -796
  27. package/dist/esm/dynamoDbCrud.service-NRSGRPDQ.mjs.map +0 -1
  28. package/dist/esm/postgreSqlCrud.service-AD2CHR2Z.mjs +0 -857
  29. package/dist/esm/postgreSqlCrud.service-AD2CHR2Z.mjs.map +0 -1
@@ -1,796 +0,0 @@
1
- import { getTableName, findIdColumnName, getPrimaryKeyColumns, PersistenceErrorWrapper } from './chunk-2H6RO6ZL.mjs';
2
- import { __privateAdd, __spreadProps, __spreadValues, FILTER_OPERATOR_MAP, DYNAMODB_OPERATORS, __privateMethod, DYNAMO_DB_UPDATE_ACTIONS } from './chunk-2OYWEFNZ.mjs';
3
- import { DynamoDBClient } from '@aws-sdk/client-dynamodb';
4
- import { DynamoDBDocumentClient, GetCommand, QueryCommand, ScanCommand, PutCommand, UpdateCommand, DeleteCommand, BatchWriteCommand } from '@aws-sdk/lib-dynamodb';
5
-
6
- var AWS_REGION = process.env.AWS_DEFAULT_REGION;
7
- var DynamoDbClientService = class {
8
- constructor(tableName) {
9
- if (!tableName)
10
- throw new Error(
11
- 'The "tableName" is required to use a DynamoDbClientService.'
12
- );
13
- this.tableName = tableName;
14
- const client = new DynamoDBClient({ region: AWS_REGION });
15
- this.dynamoDBClient = DynamoDBDocumentClient.from(client, {
16
- marshallOptions: {
17
- removeUndefinedValues: true
18
- }
19
- });
20
- }
21
- /**
22
- * Get an item by key
23
- * @param {Object} keyObject - Ex: { jobId: 1234 }
24
- * @param {GetCommandInput} options
25
- */
26
- async getByKey(keyObject, options = {}) {
27
- const params = __spreadValues({
28
- TableName: this.tableName,
29
- Key: keyObject
30
- }, options);
31
- const result = await this.dynamoDBClient.send(new GetCommand(params));
32
- return result.Item;
33
- }
34
- /**
35
- * Query a table
36
- * @param {QueryCommandInput} options
37
- */
38
- async query(options = {}) {
39
- const params = __spreadValues({
40
- TableName: this.tableName
41
- }, options);
42
- const result = await this.dynamoDBClient.send(new QueryCommand(params));
43
- if (result.$metadata) delete result.$metadata;
44
- return result;
45
- }
46
- /**
47
- * Scan a table
48
- * @param {ScanInput} options
49
- */
50
- async scan(input) {
51
- const params = __spreadProps(__spreadValues({}, input), {
52
- TableName: this.tableName
53
- });
54
- const command = new ScanCommand(params);
55
- const response = await this.dynamoDBClient.send(command);
56
- if (response.$metadata) delete response.$metadata;
57
- return response;
58
- }
59
- /**
60
- * Create/Replace a item object
61
- * To take care:
62
- * - https://stackoverflow.com/questions/43667229/difference-between-dynamodb-putitem-vs-updateitem
63
- * @param {Object} input
64
- */
65
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
66
- async put(input) {
67
- const params = {
68
- TableName: this.tableName,
69
- Item: input,
70
- ReturnValues: "NONE"
71
- };
72
- return await this.dynamoDBClient.send(new PutCommand(params));
73
- }
74
- /**
75
- * Update a item object
76
- * To take care:
77
- * - https://stackoverflow.com/questions/43667229/difference-between-dynamodb-putitem-vs-updateitem
78
- * @param {Object} keyObject - Ex: { jobId: 1234 }
79
- * @param {UpdateCommandInput} updateObject
80
- */
81
- async update(keyObject, options = {}) {
82
- const params = __spreadValues({
83
- TableName: this.tableName,
84
- Key: keyObject,
85
- ReturnValues: "NONE"
86
- }, options);
87
- return await this.dynamoDBClient.send(new UpdateCommand(params));
88
- }
89
- /**
90
- * Delete/Remove an item object
91
- */
92
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
93
- async remove(keyObject) {
94
- const params = {
95
- TableName: this.tableName,
96
- Key: keyObject,
97
- ReturnValues: "NONE"
98
- };
99
- return await this.dynamoDBClient.send(new DeleteCommand(params));
100
- }
101
- batchWrittenPut(data) {
102
- const putRequests = data.map((item) => ({
103
- PutRequest: {
104
- Item: item
105
- }
106
- }));
107
- const params = {
108
- RequestItems: {
109
- [this.tableName]: putRequests
110
- }
111
- };
112
- const insertCommand = new BatchWriteCommand(params);
113
- return this.dynamoDBClient.send(insertCommand);
114
- }
115
- buildDeleteRequestKeys(filters) {
116
- const deleteRequestKeys = {};
117
- filters.forEach((filter) => {
118
- deleteRequestKeys[filter.attribute] = filter.value;
119
- });
120
- return deleteRequestKeys;
121
- }
122
- async batchRemove(filterGroups) {
123
- if (!(filterGroups == null ? void 0 : filterGroups.length)) return;
124
- const deleteRequests = filterGroups.map((filterGroup) => ({
125
- DeleteRequest: {
126
- Key: this.buildDeleteRequestKeys(filterGroup)
127
- }
128
- }));
129
- const params = {
130
- RequestItems: {
131
- [this.tableName]: deleteRequests
132
- }
133
- };
134
- await this.dynamoDBClient.send(new BatchWriteCommand(params));
135
- }
136
- async updateExpressions(keyObject, options = {}) {
137
- const params = __spreadValues({
138
- TableName: this.tableName,
139
- Key: keyObject
140
- }, options);
141
- return await this.dynamoDBClient.send(new UpdateCommand(params));
142
- }
143
- };
144
-
145
- // src/services/cruds/dynamodb/queryBuilderCondition.service.ts
146
- var QueryBuilderConditionService = class {
147
- constructor(query) {
148
- this.tempKey = "";
149
- this.tempLogicOperator = null;
150
- this.wheres = [];
151
- this.filters = [];
152
- this.updates = [];
153
- this.attributeNames = {};
154
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
155
- this.attributeValues = {};
156
- this.query = query;
157
- this.command = {};
158
- }
159
- get() {
160
- this.build();
161
- return this.command;
162
- }
163
- setKey(key) {
164
- this.tempKey = key;
165
- return this;
166
- }
167
- setTmpLogicOp(logicOp) {
168
- this.tempLogicOperator = logicOp;
169
- return this;
170
- }
171
- setConfig(config) {
172
- this.config = config;
173
- return this;
174
- }
175
- from(methodName) {
176
- this.queryFrom = methodName;
177
- return this;
178
- }
179
- eq(keyValue) {
180
- const { key, value } = this.generateKeyValue(keyValue);
181
- let expression = `${key} = ${value}`;
182
- if (this.tempLogicOperator)
183
- expression = { expression, logicOperator: this.tempLogicOperator, config: this.config };
184
- this.setExpression(expression);
185
- return this.query;
186
- }
187
- notEq(keyValue) {
188
- const { key, value } = this.generateKeyValue(keyValue);
189
- let expression = `${key} <> ${value}`;
190
- if (this.tempLogicOperator)
191
- expression = { expression, logicOperator: this.tempLogicOperator, config: this.config };
192
- this.setExpression(expression);
193
- return this.query;
194
- }
195
- contains(keyValue) {
196
- const { key, value } = this.generateKeyValue(keyValue);
197
- let expression = `contains(${key}, ${value})`;
198
- if (this.tempLogicOperator)
199
- expression = { expression, logicOperator: this.tempLogicOperator, config: this.config };
200
- this.setExpression(expression);
201
- return this.query;
202
- }
203
- notContains(keyValue) {
204
- const { key, value } = this.generateKeyValue(keyValue);
205
- let expression = `NOT contains(${key}, ${value})`;
206
- if (this.tempLogicOperator)
207
- expression = { expression, logicOperator: this.tempLogicOperator, config: this.config };
208
- this.setExpression(expression);
209
- return this.query;
210
- }
211
- in(keyValue) {
212
- const keyValues = Array.isArray(keyValue) ? keyValue : [keyValue];
213
- const { key, value } = this.generateKeyValue(keyValues);
214
- let expression = `${key} IN (${value})`;
215
- if (this.tempLogicOperator)
216
- expression = { expression, logicOperator: this.tempLogicOperator, config: this.config };
217
- this.setExpression(expression);
218
- return this.query;
219
- }
220
- beginsWith(keyValue) {
221
- const { key, value } = this.generateKeyValue(keyValue);
222
- let expression = `begins_with(${key}, ${value})`;
223
- if (this.tempLogicOperator)
224
- expression = { expression, logicOperator: this.tempLogicOperator, config: this.config };
225
- this.setExpression(expression);
226
- return this.query;
227
- }
228
- project(keyValue) {
229
- const key = `#${keyValue}`;
230
- this.attributeNames[key] = keyValue;
231
- return key;
232
- }
233
- gt(keyValue) {
234
- const { key, value } = this.generateKeyValue(keyValue);
235
- let expression = `${key} > ${value}`;
236
- if (this.tempLogicOperator)
237
- expression = { expression, logicOperator: this.tempLogicOperator, config: this.config };
238
- this.setExpression(expression);
239
- return this.query;
240
- }
241
- gte(keyValue) {
242
- const { key, value } = this.generateKeyValue(keyValue);
243
- let expression = `${key} >= ${value}`;
244
- if (this.tempLogicOperator)
245
- expression = { expression, logicOperator: this.tempLogicOperator, config: this.config };
246
- this.setExpression(expression);
247
- return this.query;
248
- }
249
- lte(keyValue) {
250
- const { key, value } = this.generateKeyValue(keyValue);
251
- let expression = `${key} <= ${value}`;
252
- if (this.tempLogicOperator)
253
- expression = { expression, logicOperator: this.tempLogicOperator, config: this.config };
254
- this.setExpression(expression);
255
- return this.query;
256
- }
257
- lt(keyValue) {
258
- const { key, value } = this.generateKeyValue(keyValue);
259
- let expression = `${key} < ${value}`;
260
- if (this.tempLogicOperator)
261
- expression = { expression, logicOperator: this.tempLogicOperator, config: this.config };
262
- this.setExpression(expression);
263
- return this.query;
264
- }
265
- attribute_exists(keyValue) {
266
- const { key } = this.generateKeyValue(keyValue, null, true);
267
- let expression = `attribute_exists(${key})`;
268
- if (this.tempLogicOperator)
269
- expression = { expression, logicOperator: this.tempLogicOperator, config: this.config };
270
- this.setExpression(expression);
271
- return this.query;
272
- }
273
- attribute_not_exists(keyValue) {
274
- const { key } = this.generateKeyValue(keyValue, null, true);
275
- let expression = `attribute_not_exists(${key})`;
276
- if (this.tempLogicOperator)
277
- expression = { expression, logicOperator: this.tempLogicOperator, config: this.config };
278
- this.setExpression(expression);
279
- return this.query;
280
- }
281
- between(keyValues) {
282
- const isValidValues = Array.isArray(keyValues) && (keyValues == null ? void 0 : keyValues.length) === 2;
283
- if (!isValidValues)
284
- throw new Error(
285
- "The value for between filter operator should be an Array with 2 values."
286
- );
287
- const { key, value } = this.generateKeyValue(keyValues, " AND");
288
- let expression = `${key} between ${value}`;
289
- if (this.tempLogicOperator)
290
- expression = { expression, logicOperator: this.tempLogicOperator, config: this.config };
291
- this.setExpression(expression);
292
- return this.query;
293
- }
294
- setExpression(expression) {
295
- switch (this.queryFrom) {
296
- case "filter" /* filter */:
297
- this.filters.push(expression);
298
- break;
299
- case "update" /* update */:
300
- this.updates.push(expression);
301
- break;
302
- default:
303
- this.wheres.push(expression);
304
- break;
305
- }
306
- }
307
- generateKeyValue(value, separatorCharacter = ",", omitAttributeValues = false) {
308
- const keyExpression = `#${this.tempKey}1`;
309
- this.attributeNames[keyExpression] = this.tempKey;
310
- if (Array.isArray(value)) {
311
- const valueExpressions = value.map((val, index) => {
312
- let valueExpression = `:${this.tempKey}${index + 1}1`;
313
- for (const [i] of Object.entries(this.attributeValues)) {
314
- if (i === valueExpression) valueExpression += "1";
315
- }
316
- this.attributeValues[valueExpression] = val;
317
- return valueExpression;
318
- });
319
- return {
320
- key: keyExpression,
321
- value: valueExpressions.join(`${separatorCharacter} `)
322
- };
323
- } else {
324
- let valueExpression = `:${this.tempKey}1`;
325
- if (valueExpression in this.attributeValues) {
326
- for (const [index] of Object.entries(this.attributeValues)) {
327
- if (index === valueExpression) valueExpression += "1";
328
- }
329
- }
330
- if (!omitAttributeValues)
331
- this.attributeValues[valueExpression] = value;
332
- return { key: keyExpression, value: valueExpression };
333
- }
334
- }
335
- build() {
336
- var _a;
337
- if (this.wheres.length > 0) {
338
- const keyConditionExpression = this.wheres.join(" AND ");
339
- this.command["KeyConditionExpression"] = keyConditionExpression;
340
- }
341
- if (this.filters.length > 0) {
342
- let filterExpression = "";
343
- (_a = this.filters) == null ? void 0 : _a.forEach((filter, index) => {
344
- var _a2, _b;
345
- if (filter == null ? void 0 : filter.logicOperator) {
346
- if ((_a2 = filter == null ? void 0 : filter.config) == null ? void 0 : _a2.openExpression) {
347
- filterExpression = filterExpression.replace(/\s+(AND|OR)\s*$/, ` ${filter.config.parentKey} (`);
348
- if (filterExpression === "") filterExpression += "(";
349
- filterExpression += `${filter.expression} ${filter.logicOperator} `;
350
- } else if ((_b = filter == null ? void 0 : filter.config) == null ? void 0 : _b.closeExpression) {
351
- filterExpression += `${filter.expression}) ${filter.config.parentKey} `;
352
- } else {
353
- filterExpression += `${filter.expression} ${filter.logicOperator} `;
354
- }
355
- }
356
- });
357
- filterExpression = filterExpression.replace(/\s+(AND|OR)\s*$/, "");
358
- this.command["FilterExpression"] = filterExpression;
359
- }
360
- if (this.updates.length > 0) {
361
- const filterExpression = this.updates.join(", ");
362
- this.command["UpdateExpression"] = `SET ${filterExpression}`;
363
- }
364
- if (Object.values(this.attributeNames).length > 0)
365
- this.command["ExpressionAttributeNames"] = this.attributeNames;
366
- if (Object.values(this.attributeValues).length > 0)
367
- this.command["ExpressionAttributeValues"] = this.attributeValues;
368
- }
369
- };
370
-
371
- // src/services/cruds/dynamodb/queryBuilder.service.ts
372
- var QueryBuilderService = class {
373
- constructor(useScan = false) {
374
- this.useScan = useScan;
375
- this.command = {};
376
- this.condition = new QueryBuilderConditionService(this);
377
- }
378
- get() {
379
- const condition = this.condition.get();
380
- return __spreadValues(__spreadValues({}, this.command), condition);
381
- }
382
- limit(num) {
383
- this.command.Limit = num;
384
- return this;
385
- }
386
- usingIndex(indexName) {
387
- this.command.IndexName = indexName;
388
- return this;
389
- }
390
- ascending() {
391
- if (!this.useScan) this.command.ScanIndexForward = true;
392
- return this;
393
- }
394
- descending() {
395
- if (!this.useScan) this.command.ScanIndexForward = false;
396
- return this;
397
- }
398
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
399
- startKey(lastEvaluatedKey) {
400
- this.command.ExclusiveStartKey = lastEvaluatedKey;
401
- return this;
402
- }
403
- projection(fields = []) {
404
- if (!fields.length) return this;
405
- const expression = [];
406
- fields.forEach((field) => {
407
- const key = this.condition.project(field);
408
- expression.push(key);
409
- });
410
- this.command.ProjectionExpression = expression.join(",");
411
- return this;
412
- }
413
- where(keyName) {
414
- this.condition.setKey(keyName).setTmpLogicOp(null).from("where" /* where */);
415
- return this.condition;
416
- }
417
- filter(keyName, logicOperator = "AND", config) {
418
- this.condition.setKey(keyName).setTmpLogicOp(logicOperator).setConfig(config).from("filter" /* filter */);
419
- return this.condition;
420
- }
421
- update(attribute) {
422
- for (const [key, value] of Object.entries(attribute)) {
423
- this.condition.setKey(key).from("update" /* update */);
424
- this.condition.eq(value);
425
- }
426
- return this;
427
- }
428
- consistentRead(consistentRead) {
429
- this.command.ConsistentRead = consistentRead;
430
- return this;
431
- }
432
- count() {
433
- this.command.Select = "COUNT" /* COUNT */;
434
- return this;
435
- }
436
- };
437
-
438
- // src/services/cruds/dynamodb/dynamoDbCrud.service.ts
439
- var _DynamoDbCrudService_instances, prepareAndExecuteUpdateExpression_fn, buildUpdateExpressionQuery_fn, getKeyObjectForUpdateExpression_fn, getUpdateExpressionOptions_fn, extractUpdateExpressionAttributesAndNames_fn;
440
- var DynamoDbCrudService = class {
441
- constructor(tableSchema) {
442
- this.tableSchema = tableSchema;
443
- __privateAdd(this, _DynamoDbCrudService_instances);
444
- this.dynamoDbClientService = new DynamoDbClientService(this.tableName);
445
- }
446
- get tableName() {
447
- return getTableName(this.tableSchema.table);
448
- }
449
- get idColumnName() {
450
- return findIdColumnName(this.tableSchema.columns);
451
- }
452
- get defaultPrimaryKeys() {
453
- return getPrimaryKeyColumns(this.tableSchema.columns);
454
- }
455
- async create(data) {
456
- var _a;
457
- if (Array.isArray(data)) {
458
- const response = await this.dynamoDbClientService.batchWrittenPut(data);
459
- return {
460
- unprocessedItems: (_a = response.UnprocessedItems) != null ? _a : []
461
- };
462
- } else {
463
- await this.dynamoDbClientService.put(data);
464
- return data;
465
- }
466
- }
467
- // eslint-disable-next-line @typescript-eslint/no-unused-vars, no-unused-vars
468
- runQuery(queryCommand) {
469
- throw new Error("Method not implemented.");
470
- }
471
- find(options = {}) {
472
- var _a, _b, _c, _d;
473
- const query = new QueryBuilderService(options.useScan);
474
- if ((_a = options.index) == null ? void 0 : _a.indexName)
475
- query.usingIndex((_b = options.index) == null ? void 0 : _b.indexName);
476
- this.applySorting(query, options.sorting, (_c = options.index) == null ? void 0 : _c.indexName);
477
- this.applyPagination(query, options.pagination);
478
- if (options.consistentRead)
479
- query.consistentRead(options.consistentRead);
480
- if (options.fields) query.projection(options.fields);
481
- this.applyFilters(query, options);
482
- if (options.aggregateFunction === "COUNT" /* COUNT */)
483
- query.count();
484
- return this.fetchResults(
485
- query.get(),
486
- (_d = options.pagination) == null ? void 0 : _d.limit,
487
- options.useScan
488
- ).then((res) => {
489
- var _a2, _b2;
490
- const pagination = {};
491
- if (res.lastEvaluatedKey) pagination.from = res.lastEvaluatedKey;
492
- if ((_a2 = options.pagination) == null ? void 0 : _a2.limit)
493
- pagination.limit = (_b2 = options.pagination) == null ? void 0 : _b2.limit;
494
- return {
495
- items: res.items,
496
- pagination,
497
- count: res.count
498
- };
499
- });
500
- }
501
- async fetchResults(command, limit = 100, useScan = false) {
502
- var _a, _b;
503
- let results = [];
504
- let lastEvaluatedKey = {};
505
- let rowsCount = 0;
506
- do {
507
- const result = await this.fetchBatch(
508
- command,
509
- useScan,
510
- lastEvaluatedKey
511
- );
512
- const rows = (_a = result.Items) != null ? _a : [];
513
- results = results.concat(rows);
514
- lastEvaluatedKey = (_b = result.LastEvaluatedKey) != null ? _b : {};
515
- rowsCount += result.Count || rows.length;
516
- } while (rowsCount < limit && this.isNotEmptyObject(lastEvaluatedKey));
517
- const encryptedLastEvaluatedKey = this.isNotEmptyObject(
518
- lastEvaluatedKey
519
- ) ? this.encryptPaginationKey(lastEvaluatedKey) : null;
520
- return {
521
- items: results,
522
- lastEvaluatedKey: encryptedLastEvaluatedKey,
523
- count: rowsCount
524
- };
525
- }
526
- async fetchBatch(command, useScan, lastEvaluatedKey) {
527
- var _a, _b, _c;
528
- if (this.isNotEmptyObject(lastEvaluatedKey))
529
- command.ExclusiveStartKey = lastEvaluatedKey;
530
- const result = await (useScan ? this.dynamoDbClientService.scan(command) : this.dynamoDbClientService.query(command));
531
- if (command.Select !== "COUNT" /* COUNT */) {
532
- command.Limit = ((_a = command.Limit) != null ? _a : 0) - ((_c = (_b = result.Items) == null ? void 0 : _b.length) != null ? _c : 0);
533
- }
534
- return result;
535
- }
536
- applyPagination(query, pagination) {
537
- if (pagination == null ? void 0 : pagination.limit) query.limit(pagination.limit);
538
- if (pagination == null ? void 0 : pagination.from)
539
- query.startKey(this.decryptPaginationKey(pagination.from));
540
- }
541
- async findAll(options = {}, allResults = [], rowsCount = 0) {
542
- const { items, pagination, count } = await this.find(options);
543
- allResults.push(...items);
544
- rowsCount += count;
545
- if (pagination == null ? void 0 : pagination.from)
546
- await this.findAll(__spreadProps(__spreadValues({}, options), { pagination }), allResults);
547
- return {
548
- items: allResults,
549
- pagination: null,
550
- count: rowsCount
551
- };
552
- }
553
- async findCount(options = {}) {
554
- var _a;
555
- const findOptions = __spreadProps(__spreadValues({}, options), {
556
- aggregateFunction: "COUNT" /* COUNT */
557
- });
558
- if ((_a = options.pagination) == null ? void 0 : _a.from) {
559
- return this.find(findOptions).then((res) => res.count);
560
- } else {
561
- return this.findAll(findOptions).then((res) => res.count);
562
- }
563
- }
564
- buildFindItemQuery(options) {
565
- var _a;
566
- const query = new QueryBuilderService();
567
- if ((_a = options.index) == null ? void 0 : _a.indexName) query.usingIndex(options.index.indexName);
568
- this.applyFilters(query, options);
569
- query.projection(options.fields);
570
- query.limit(1);
571
- return query;
572
- }
573
- findItem(options) {
574
- const query = this.buildFindItemQuery(options);
575
- return this.dynamoDbClientService.query(query.get()).then((result) => {
576
- var _a;
577
- if ((_a = result.Items) == null ? void 0 : _a.length) return result.Items[0];
578
- if (options.throwErrorIfNull) throw new Error("NOT_FOUND");
579
- return null;
580
- });
581
- }
582
- applyWhereFilter(query, filter) {
583
- var _a, _b;
584
- const operator = FILTER_OPERATOR_MAP[(_b = (_a = filter.operator) == null ? void 0 : _a.toUpperCase()) != null ? _b : DYNAMODB_OPERATORS.EQUAL];
585
- query.where(filter.attribute)[operator](filter.value);
586
- }
587
- applyFilterFilter(query, filter, logicOperator = "AND", config) {
588
- var _a, _b;
589
- const operator = FILTER_OPERATOR_MAP[(_b = (_a = filter.operator) == null ? void 0 : _a.toUpperCase()) != null ? _b : DYNAMODB_OPERATORS.EQUAL];
590
- query.filter(filter.attribute, logicOperator, config)[operator](filter.value);
591
- }
592
- applyFilters(query, options) {
593
- if (Array.isArray(options.filters)) {
594
- this.applySimpleFilters(query, options);
595
- } else {
596
- this.applyCompoundFilters(query, options);
597
- }
598
- }
599
- applySimpleFilters(query, options) {
600
- var _a, _b;
601
- const queryIndexColumns = (_b = (_a = options.index) == null ? void 0 : _a.columns) != null ? _b : [];
602
- const defaultWhereProperties = this.defaultPrimaryKeys;
603
- const whereProperties = (queryIndexColumns == null ? void 0 : queryIndexColumns.length) ? queryIndexColumns : defaultWhereProperties;
604
- const filters = options.filters;
605
- filters.forEach((filter) => {
606
- const isWhereProperty = whereProperties.includes(filter.attribute);
607
- isWhereProperty && !options.useScan ? this.applyWhereFilter(query, filter) : this.applyFilterFilter(query, filter);
608
- });
609
- }
610
- applyCompoundFilters(query, options) {
611
- if (!options.filters) return;
612
- this.buildFilterExpression(query, options);
613
- }
614
- buildFilterExpression(query, options, parentKey) {
615
- var _a;
616
- const compositeFilters = options.filters;
617
- const queryIndexColumns = ((_a = options.index) == null ? void 0 : _a.columns) || [];
618
- const defaultWhereProperties = this.defaultPrimaryKeys;
619
- const whereProperties = (queryIndexColumns == null ? void 0 : queryIndexColumns.length) ? queryIndexColumns : defaultWhereProperties;
620
- for (const [key, value] of Object.entries(compositeFilters)) {
621
- value.forEach(
622
- (filter, index) => {
623
- const isCompositeFilter = "OR" in filter || "AND" in filter;
624
- if (isCompositeFilter) {
625
- const newOptions = __spreadProps(__spreadValues({}, options), {
626
- filters: filter
627
- });
628
- this.buildFilterExpression(query, newOptions, key);
629
- } else {
630
- const simpleFilter = filter;
631
- const isWhereProperty = whereProperties.includes(
632
- simpleFilter.attribute
633
- );
634
- let config;
635
- if (parentKey) {
636
- config = {
637
- parentKey,
638
- openExpression: index === 0,
639
- closeExpression: index === value.length - 1
640
- };
641
- }
642
- isWhereProperty && !options.useScan ? this.applyWhereFilter(query, simpleFilter) : this.applyFilterFilter(
643
- query,
644
- simpleFilter,
645
- key,
646
- config
647
- );
648
- }
649
- }
650
- );
651
- }
652
- }
653
- applySorting(query, sorting, sortIndex) {
654
- if (sorting == null ? void 0 : sorting.length) {
655
- if (sortIndex) query.usingIndex(sortIndex);
656
- if (sorting[0].direction === "DESC") {
657
- query.descending();
658
- } else {
659
- query.ascending();
660
- }
661
- }
662
- }
663
- isNotEmptyObject(obj) {
664
- return obj !== null && typeof obj === "object" && Object.keys(obj).length > 0;
665
- }
666
- encryptPaginationKey(key) {
667
- const jsonKey = JSON.stringify(key);
668
- return Buffer.from(jsonKey).toString("base64");
669
- }
670
- decryptPaginationKey(encodedKey) {
671
- const decodedKey = Buffer.from(encodedKey, "base64").toString("utf-8");
672
- return JSON.parse(decodedKey);
673
- }
674
- async update(filters, data, { replace = false }) {
675
- const savedRecord = await this.findItem({
676
- filters
677
- });
678
- const newData = __spreadValues(__spreadValues({}, savedRecord), data);
679
- await this.dynamoDbClientService.put(newData);
680
- return newData;
681
- }
682
- async remove(filters, options) {
683
- if (options == null ? void 0 : options.filterGroups) {
684
- await this.dynamoDbClientService.batchRemove(
685
- filters
686
- );
687
- } else {
688
- const key = filters.reduce((obj, item) => {
689
- const property = item.attribute;
690
- obj[property] = item.value;
691
- return obj;
692
- }, {});
693
- await this.dynamoDbClientService.remove(key);
694
- }
695
- }
696
- async updateExpressions(filters, actions, options) {
697
- try {
698
- return await __privateMethod(this, _DynamoDbCrudService_instances, prepareAndExecuteUpdateExpression_fn).call(this, filters, actions, options);
699
- } catch (error) {
700
- PersistenceErrorWrapper(error);
701
- }
702
- }
703
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
704
- runRawQuery(query, params) {
705
- throw new Error("Method not implemented.");
706
- }
707
- };
708
- _DynamoDbCrudService_instances = new WeakSet();
709
- prepareAndExecuteUpdateExpression_fn = async function(filters, actions, options) {
710
- const queryObject = __privateMethod(this, _DynamoDbCrudService_instances, buildUpdateExpressionQuery_fn).call(this, { filters }).get();
711
- const primaryKeys = this.defaultPrimaryKeys;
712
- const keyObject = __privateMethod(this, _DynamoDbCrudService_instances, getKeyObjectForUpdateExpression_fn).call(this, queryObject, primaryKeys);
713
- const updateExpressions = [];
714
- Object.keys(actions).forEach((action) => {
715
- const actionUpdateExpression = __privateMethod(this, _DynamoDbCrudService_instances, extractUpdateExpressionAttributesAndNames_fn).call(this, actions, action);
716
- updateExpressions.push(actionUpdateExpression);
717
- });
718
- const dbParams = __spreadValues({
719
- UpdateExpression: updateExpressions.join(" ")
720
- }, __privateMethod(this, _DynamoDbCrudService_instances, getUpdateExpressionOptions_fn).call(this, options));
721
- const { ExpressionAttributeValues, ExpressionAttributeNames } = queryObject;
722
- if (Object.keys(ExpressionAttributeValues).length > 0) {
723
- dbParams["ExpressionAttributeValues"] = __spreadValues(__spreadValues({}, ExpressionAttributeValues), dbParams.ExpressionAttributeValues);
724
- }
725
- if (Object.keys(ExpressionAttributeNames).length > 0) {
726
- dbParams["ExpressionAttributeNames"] = __spreadValues(__spreadValues({}, ExpressionAttributeNames), dbParams.ExpressionAttributeNames);
727
- }
728
- if (queryObject.FilterExpression)
729
- dbParams["ConditionExpression"] = queryObject.FilterExpression;
730
- return this.dynamoDbClientService.updateExpressions(
731
- keyObject,
732
- dbParams
733
- );
734
- };
735
- buildUpdateExpressionQuery_fn = function(options) {
736
- var _a;
737
- const query = new QueryBuilderService();
738
- if ((_a = options.index) == null ? void 0 : _a.indexName) query.usingIndex(options.index.indexName);
739
- this.applyFilters(query, options);
740
- return query;
741
- };
742
- getKeyObjectForUpdateExpression_fn = function(queryObject, primaryKeys) {
743
- const keyObject = {};
744
- Object.keys(queryObject.ExpressionAttributeNames).forEach(
745
- (attribute) => {
746
- const sanitizedAttribute = attribute.replace("#", "").replace("1", "");
747
- if (primaryKeys.includes(sanitizedAttribute)) {
748
- const valueName = `:${sanitizedAttribute}1`;
749
- keyObject[sanitizedAttribute] = queryObject.ExpressionAttributeValues[valueName];
750
- delete queryObject.ExpressionAttributeValues[valueName];
751
- delete queryObject.ExpressionAttributeNames[attribute];
752
- }
753
- }
754
- );
755
- return keyObject;
756
- };
757
- getUpdateExpressionOptions_fn = function(options) {
758
- const updateExprOptions = {
759
- ReturnValues: options.returnValues
760
- };
761
- if (options.expressionAttributeNames)
762
- updateExprOptions.ExpressionAttributeNames = options.expressionAttributeNames;
763
- if (options.expressionAttributeValues)
764
- updateExprOptions.ExpressionAttributeValues = options.expressionAttributeValues;
765
- return updateExprOptions;
766
- };
767
- extractUpdateExpressionAttributesAndNames_fn = function(actions, actionType) {
768
- const actionUpdateExpressions = [];
769
- actions[actionType].forEach((action) => {
770
- switch (actionType) {
771
- case DYNAMO_DB_UPDATE_ACTIONS.DELETE:
772
- case DYNAMO_DB_UPDATE_ACTIONS.REMOVE:
773
- actionUpdateExpressions.push(`${action.path}`);
774
- break;
775
- case DYNAMO_DB_UPDATE_ACTIONS.ADD:
776
- case DYNAMO_DB_UPDATE_ACTIONS.SET:
777
- {
778
- let operator = "";
779
- if (actionType == DYNAMO_DB_UPDATE_ACTIONS.SET)
780
- operator = "=";
781
- actionUpdateExpressions.push(
782
- `${action.path} ${operator}${action.value}`
783
- );
784
- }
785
- break;
786
- }
787
- });
788
- const actionUpdateExpression = `${actionType} ${actionUpdateExpressions.join(
789
- ", "
790
- )}`;
791
- return actionUpdateExpression;
792
- };
793
-
794
- export { DynamoDbCrudService };
795
- //# sourceMappingURL=dynamoDbCrud.service-NRSGRPDQ.mjs.map
796
- //# sourceMappingURL=dynamoDbCrud.service-NRSGRPDQ.mjs.map