mocody 0.4.37 → 0.5.0-alpha

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 (83) hide show
  1. package/dist/core/base-schema.d.ts +13 -13
  2. package/dist/core/base-schema.js +11 -11
  3. package/dist/couch/couch-data-operation.d.ts +92 -92
  4. package/dist/couch/couch-data-operation.js +580 -580
  5. package/dist/couch/couch-data-operation.js.map +1 -1
  6. package/dist/couch/couch-filter-query-operation.d.ts +45 -47
  7. package/dist/couch/couch-filter-query-operation.js +371 -438
  8. package/dist/couch/couch-filter-query-operation.js.map +1 -1
  9. package/dist/couch/couch-initializer.d.ts +126 -126
  10. package/dist/couch/couch-initializer.js +189 -189
  11. package/dist/couch/couch-initializer.js.map +1 -1
  12. package/dist/couch/couch-manage-table.d.ts +46 -46
  13. package/dist/couch/couch-manage-table.js +103 -103
  14. package/dist/couch/couch-manage-table.js.map +1 -1
  15. package/dist/dynamo/dynamo-data-operation.d.ts +102 -99
  16. package/dist/dynamo/dynamo-data-operation.js +932 -797
  17. package/dist/dynamo/dynamo-data-operation.js.map +1 -1
  18. package/dist/dynamo/dynamo-filter-query-operation.d.ts +29 -29
  19. package/dist/dynamo/dynamo-filter-query-operation.js +603 -693
  20. package/dist/dynamo/dynamo-filter-query-operation.js.map +1 -1
  21. package/dist/dynamo/dynamo-filter-query-partiql-operation.d.ts +22 -0
  22. package/dist/dynamo/dynamo-filter-query-partiql-operation.js +457 -0
  23. package/dist/dynamo/dynamo-filter-query-partiql-operation.js.map +1 -0
  24. package/dist/dynamo/dynamo-helper.d.ts +1 -1
  25. package/dist/dynamo/dynamo-helper.js +8 -8
  26. package/dist/dynamo/dynamo-initializer.d.ts +15 -14
  27. package/dist/dynamo/dynamo-initializer.js +66 -58
  28. package/dist/dynamo/dynamo-initializer.js.map +1 -1
  29. package/dist/dynamo/dynamo-manage-table.d.ts +33 -33
  30. package/dist/dynamo/dynamo-manage-table.js +419 -419
  31. package/dist/dynamo/dynamo-manage-table.js.map +1 -1
  32. package/dist/dynamo/dynamo-query-partiql-processor.d.ts +31 -0
  33. package/dist/dynamo/dynamo-query-partiql-processor.js +277 -0
  34. package/dist/dynamo/dynamo-query-partiql-processor.js.map +1 -0
  35. package/dist/dynamo/dynamo-query-scan-processor.d.ts +25 -25
  36. package/dist/dynamo/dynamo-query-scan-processor.js +268 -268
  37. package/dist/dynamo/dynamo-query-scan-processor.js.map +1 -1
  38. package/dist/helpers/base-joi-helper.d.ts +2 -2
  39. package/dist/helpers/base-joi-helper.js +12 -12
  40. package/dist/helpers/constants.d.ts +3 -3
  41. package/dist/helpers/constants.js +6 -6
  42. package/dist/helpers/errors.d.ts +13 -13
  43. package/dist/helpers/errors.js +38 -38
  44. package/dist/helpers/logging-service.d.ts +9 -9
  45. package/dist/helpers/logging-service.js +53 -53
  46. package/dist/helpers/logging-service.js.map +1 -1
  47. package/dist/helpers/mocody-utils.d.ts +16 -16
  48. package/dist/helpers/mocody-utils.js +58 -58
  49. package/dist/helpers/query-validator.d.ts +20 -20
  50. package/dist/helpers/query-validator.js +96 -96
  51. package/dist/helpers/util-service.d.ts +29 -29
  52. package/dist/helpers/util-service.js +155 -155
  53. package/dist/index.d.ts +12 -12
  54. package/dist/index.js +23 -23
  55. package/dist/model/index.d.ts +42 -42
  56. package/dist/model/index.js +6 -6
  57. package/dist/mongo/mongo-data-operation.d.ts +90 -90
  58. package/dist/mongo/mongo-data-operation.js +607 -607
  59. package/dist/mongo/mongo-data-operation.js.map +1 -1
  60. package/dist/mongo/mongo-filter-query-operation.d.ts +45 -47
  61. package/dist/mongo/mongo-filter-query-operation.js +368 -433
  62. package/dist/mongo/mongo-filter-query-operation.js.map +1 -1
  63. package/dist/mongo/mongo-initializer.d.ts +16 -16
  64. package/dist/mongo/mongo-initializer.js +47 -47
  65. package/dist/mongo/mongo-initializer.js.map +1 -1
  66. package/dist/mongo/mongo-table-manager.d.ts +31 -31
  67. package/dist/mongo/mongo-table-manager.js +104 -104
  68. package/dist/mongo/mongo-table-manager.js.map +1 -1
  69. package/dist/pouch/pouch-data-operation.d.ts +90 -90
  70. package/dist/pouch/pouch-data-operation.js +583 -583
  71. package/dist/pouch/pouch-data-operation.js.map +1 -1
  72. package/dist/pouch/pouch-filter-query-operation.d.ts +45 -47
  73. package/dist/pouch/pouch-filter-query-operation.js +371 -438
  74. package/dist/pouch/pouch-filter-query-operation.js.map +1 -1
  75. package/dist/pouch/pouch-initializer.d.ts +111 -109
  76. package/dist/pouch/pouch-initializer.js +357 -357
  77. package/dist/pouch/pouch-initializer.js.map +1 -1
  78. package/dist/pouch/pouch-manage-table.d.ts +35 -35
  79. package/dist/pouch/pouch-manage-table.js +99 -99
  80. package/dist/pouch/pouch-manage-table.js.map +1 -1
  81. package/dist/type/index.d.ts +118 -119
  82. package/dist/type/index.js +2 -2
  83. package/package.json +17 -16
@@ -1,608 +1,608 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.MongoDataOperation = void 0;
4
- const tslib_1 = require("tslib");
5
- const mocody_utils_1 = require("./../helpers/mocody-utils");
6
- const constants_1 = require("./../helpers/constants");
7
- const util_service_1 = require("./../helpers/util-service");
8
- const logging_service_1 = require("./../helpers/logging-service");
9
- const model_1 = require("../model");
10
- const joi_1 = tslib_1.__importDefault(require("joi"));
11
- const base_schema_1 = require("../core/base-schema");
12
- const errors_1 = require("../helpers/errors");
13
- const base_joi_helper_1 = require("../helpers/base-joi-helper");
14
- const mongo_filter_query_operation_1 = require("./mongo-filter-query-operation");
15
- const mongo_table_manager_1 = require("./mongo-table-manager");
16
- const mongodb_1 = require("mongodb");
17
- class MongoDataOperation extends model_1.RepoModel {
18
- constructor({ schemaDef, mongoDbInitializer, secondaryIndexOptions, featureEntityValue, baseTableName, strictRequiredFields, dataKeyGenerator, }) {
19
- super();
20
- Object.defineProperty(this, "_mocody_partitionKeyFieldName", {
21
- enumerable: true,
22
- configurable: true,
23
- writable: true,
24
- value: "id"
25
- });
26
- Object.defineProperty(this, "_mocody_sortKeyFieldName", {
27
- enumerable: true,
28
- configurable: true,
29
- writable: true,
30
- value: "featureEntity"
31
- });
32
- Object.defineProperty(this, "_mocody_operationNotSuccessful", {
33
- enumerable: true,
34
- configurable: true,
35
- writable: true,
36
- value: "Operation Not Successful"
37
- });
38
- Object.defineProperty(this, "_mocody_entityFieldsKeySet", {
39
- enumerable: true,
40
- configurable: true,
41
- writable: true,
42
- value: void 0
43
- });
44
- Object.defineProperty(this, "_mocody_mongoDb", {
45
- enumerable: true,
46
- configurable: true,
47
- writable: true,
48
- value: void 0
49
- });
50
- Object.defineProperty(this, "_mocody_dataKeyGenerator", {
51
- enumerable: true,
52
- configurable: true,
53
- writable: true,
54
- value: void 0
55
- });
56
- Object.defineProperty(this, "_mocody_schema", {
57
- enumerable: true,
58
- configurable: true,
59
- writable: true,
60
- value: void 0
61
- });
62
- Object.defineProperty(this, "_mocody_tableFullName", {
63
- enumerable: true,
64
- configurable: true,
65
- writable: true,
66
- value: void 0
67
- });
68
- Object.defineProperty(this, "_mocody_strictRequiredFields", {
69
- enumerable: true,
70
- configurable: true,
71
- writable: true,
72
- value: void 0
73
- });
74
- Object.defineProperty(this, "_mocody_featureEntityValue", {
75
- enumerable: true,
76
- configurable: true,
77
- writable: true,
78
- value: void 0
79
- });
80
- Object.defineProperty(this, "_mocody_secondaryIndexOptions", {
81
- enumerable: true,
82
- configurable: true,
83
- writable: true,
84
- value: void 0
85
- });
86
- Object.defineProperty(this, "_mocody_errorHelper", {
87
- enumerable: true,
88
- configurable: true,
89
- writable: true,
90
- value: void 0
91
- });
92
- Object.defineProperty(this, "_mocody_filterQueryOperation", {
93
- enumerable: true,
94
- configurable: true,
95
- writable: true,
96
- value: new mongo_filter_query_operation_1.MongoFilterQueryOperation()
97
- });
98
- Object.defineProperty(this, "_mocody_tableManager", {
99
- enumerable: true,
100
- configurable: true,
101
- writable: true,
102
- value: void 0
103
- });
104
- this._mocody_mongoDb = mongoDbInitializer;
105
- this._mocody_dataKeyGenerator = dataKeyGenerator;
106
- this._mocody_tableFullName = baseTableName;
107
- this._mocody_featureEntityValue = featureEntityValue;
108
- this._mocody_secondaryIndexOptions = secondaryIndexOptions;
109
- this._mocody_strictRequiredFields = strictRequiredFields;
110
- this._mocody_errorHelper = new errors_1.MocodyErrorUtils();
111
- this._mocody_entityFieldsKeySet = new Set();
112
- const fullSchemaMapDef = {
113
- ...schemaDef,
114
- ...base_schema_1.coreSchemaDefinition,
115
- };
116
- Object.keys(fullSchemaMapDef).forEach((key) => {
117
- this._mocody_entityFieldsKeySet.add(key);
118
- });
119
- this._mocody_schema = joi_1.default.object().keys({
120
- ...fullSchemaMapDef,
121
- _id: joi_1.default.string().required().min(5).max(512),
122
- });
123
- }
124
- mocody_tableManager() {
125
- if (!this._mocody_tableManager) {
126
- this._mocody_tableManager = new mongo_table_manager_1.MongoManageTable({
127
- mongoDb: () => this._mocody_mongoDb(),
128
- secondaryIndexOptions: this._mocody_secondaryIndexOptions,
129
- tableFullName: this._mocody_tableFullName,
130
- partitionKeyFieldName: this._mocody_partitionKeyFieldName,
131
- sortKeyFieldName: this._mocody_sortKeyFieldName,
132
- });
133
- }
134
- return this._mocody_tableManager;
135
- }
136
- _mocody_generateDynamoTableKey() {
137
- return this._mocody_dataKeyGenerator();
138
- }
139
- async _mocody_getDbInstance() {
140
- return await this._mocody_mongoDb()
141
- .getCustomCollectionInstance(this._mocody_tableFullName);
142
- }
143
- async _mocody_getDbInstanceDefined(tableFullName) {
144
- return await this._mocody_mongoDb()
145
- .getCustomCollectionInstance(tableFullName);
146
- }
147
- _mocody_getLocalVariables() {
148
- return {
149
- partitionKeyFieldName: this._mocody_partitionKeyFieldName,
150
- sortKeyFieldName: this._mocody_sortKeyFieldName,
151
- featureEntityValue: this._mocody_featureEntityValue,
152
- secondaryIndexOptions: this._mocody_secondaryIndexOptions,
153
- strictRequiredFields: this._mocody_strictRequiredFields,
154
- };
155
- }
156
- _mocody_getNativeMongoId(dataId) {
157
- const { featureEntityValue } = this._mocody_getLocalVariables();
158
- return [featureEntityValue, dataId].join(":");
159
- }
160
- _mocody_getBaseObject({ dataId }) {
161
- const { partitionKeyFieldName, sortKeyFieldName, featureEntityValue } = this._mocody_getLocalVariables();
162
- const dataMust = {
163
- [partitionKeyFieldName]: dataId,
164
- [sortKeyFieldName]: featureEntityValue,
165
- };
166
- return dataMust;
167
- }
168
- _mocody_withConditionPassed({ item, withCondition, }) {
169
- if (item && typeof item === "object" && withCondition?.length) {
170
- const isPassed = withCondition.every(({ field, equals }) => {
171
- return item[field] !== undefined && item[field] === equals;
172
- });
173
- return isPassed;
174
- }
175
- return true;
176
- }
177
- _mocody_checkValidateMustBeAnObjectDataType(data) {
178
- if (!data || typeof data !== "object") {
179
- throw this._mocody_createGenericError(`Data MUST be valid object`);
180
- }
181
- }
182
- _mocody_checkValidateStrictRequiredFields(onDataObj) {
183
- this._mocody_checkValidateMustBeAnObjectDataType(onDataObj);
184
- const { strictRequiredFields } = this._mocody_getLocalVariables();
185
- if (strictRequiredFields?.length) {
186
- strictRequiredFields.forEach((field) => {
187
- if (onDataObj[field] === null || onDataObj[field] === undefined) {
188
- throw this._mocody_createGenericError(`Strict required field: '${field}', NOT defined`);
189
- }
190
- });
191
- }
192
- }
193
- _mocody_removeDuplicateString(list) {
194
- return Array.from(new Set(list));
195
- }
196
- _mocody_getProjectionFields({ excludeFields, fields, }) {
197
- return mocody_utils_1.MocodyUtil.getProjectionFields({
198
- excludeFields,
199
- fields,
200
- entityFields: Array.from(this._mocody_entityFieldsKeySet),
201
- });
202
- }
203
- _mocody_toMongoProjection(fields) {
204
- if (fields?.length) {
205
- const projection = {};
206
- const uniqueFields = this._mocody_removeDuplicateString(fields);
207
- uniqueFields.forEach((field) => {
208
- projection[field] = 1;
209
- });
210
- return projection;
211
- }
212
- return undefined;
213
- }
214
- async _mocody_allHelpValidateGetValue(data) {
215
- const { error, value } = this._mocody_schema.validate(data, {
216
- stripUnknown: true,
217
- });
218
- if (error) {
219
- const msg = (0, base_joi_helper_1.getJoiValidationErrors)(error) ?? "Validation error occured";
220
- throw this._mocody_errorHelper.mocody_helper_createFriendlyError(msg);
221
- }
222
- return await Promise.resolve({ validatedData: value });
223
- }
224
- _mocody_createGenericError(error) {
225
- return new errors_1.MocodyGenericError(error);
226
- }
227
- async mocody_getOneById({ dataId, withCondition, }) {
228
- this._mocody_errorHelper.mocody_helper_validateRequiredString({ dataId });
229
- const mongo = await this._mocody_getDbInstance();
230
- const nativeId = this._mocody_getNativeMongoId(dataId);
231
- const query = { _id: nativeId };
232
- const dataInDb = await mongo.findOne(query, { projection: { _id: 0 } });
233
- if (!(dataInDb?.id === dataId && dataInDb.featureEntity === this._mocody_featureEntityValue)) {
234
- return null;
235
- }
236
- const passed = this._mocody_withConditionPassed({ item: dataInDb, withCondition });
237
- if (!passed) {
238
- return null;
239
- }
240
- return dataInDb;
241
- }
242
- async mocody_getManyByIds({ dataIds, fields, excludeFields, withCondition, }) {
243
- const uniqueIds = this._mocody_removeDuplicateString(dataIds);
244
- const fullUniqueIds = uniqueIds.map((id) => this._mocody_getNativeMongoId(id));
245
- const mongo = await this._mocody_getDbInstance();
246
- const fieldKeys = this._mocody_getProjectionFields({ fields, excludeFields });
247
- if (withCondition?.length && fieldKeys?.length) {
248
- withCondition.forEach((item) => {
249
- fieldKeys.push(item.field);
250
- });
251
- }
252
- const projection = this._mocody_toMongoProjection(fieldKeys);
253
- const query = { _id: { $in: fullUniqueIds } };
254
- const dataListInDb = await mongo.find(query, { projection }).toArray();
255
- if (!dataListInDb?.length) {
256
- return [];
257
- }
258
- const dataListInDb01 = dataListInDb.map((f) => {
259
- return util_service_1.UtilService.deleteKeysFromObject({ dataObject: f, delKeys: ["_id"] });
260
- });
261
- if (withCondition?.length) {
262
- const dataFiltered = dataListInDb01.filter((item) => {
263
- const passed = this._mocody_withConditionPassed({ item, withCondition });
264
- return passed;
265
- });
266
- return dataFiltered;
267
- }
268
- return dataListInDb01;
269
- }
270
- async mocody_formatForDump({ dataList }) {
271
- const bulkData = [];
272
- for (const data of dataList) {
273
- const validatedDataWithTTL = await this.mocody_validateFormatData({ data });
274
- bulkData.push(validatedDataWithTTL);
275
- }
276
- return bulkData;
277
- }
278
- async mocody_validateFormatData({ data }) {
279
- const { validatedDataWithTTL } = await this._mocody_validateReady({ data });
280
- return JSON.stringify(validatedDataWithTTL);
281
- }
282
- async mocody_createOne({ data, fieldAliases, }) {
283
- const { validatedData, validatedDataWithTTL } = await this._mocody_validateReady({ data });
284
- mocody_utils_1.MocodyUtil.validateFieldAlias({
285
- fieldAliases,
286
- data: validatedData,
287
- featureEntity: this._mocody_featureEntityValue,
288
- });
289
- const mongo = await this._mocody_getDbInstance();
290
- const result = await mongo.insertOne(validatedDataWithTTL);
291
- if (!result?.acknowledged) {
292
- throw this._mocody_createGenericError(this._mocody_operationNotSuccessful);
293
- }
294
- const final = { ...validatedData };
295
- delete final._id;
296
- return final;
297
- }
298
- async _mocody_validateReady({ data }) {
299
- const { partitionKeyFieldName, featureEntityValue } = this._mocody_getLocalVariables();
300
- let dataId = data[partitionKeyFieldName];
301
- if (!dataId) {
302
- dataId = this._mocody_generateDynamoTableKey();
303
- }
304
- if (!(dataId && typeof dataId === "string")) {
305
- throw this._mocody_createGenericError("Invalid dataId generation");
306
- }
307
- const dataMust = this._mocody_getBaseObject({ dataId });
308
- const fullData = {
309
- ...data,
310
- ...dataMust,
311
- _id: this._mocody_getNativeMongoId(dataId),
312
- };
313
- if (fullData.featureEntity !== featureEntityValue) {
314
- throw this._mocody_createGenericError("FeatureEntity mismatched");
315
- }
316
- const { validatedData } = await this._mocody_allHelpValidateGetValue(fullData);
317
- this._mocody_checkValidateStrictRequiredFields(validatedData);
318
- const validatedDataWithTTL = this._mocody_formatTTL(validatedData);
319
- return { validatedData, validatedDataWithTTL };
320
- }
321
- _mocody_formatTTL(fullData) {
322
- if (fullData?.dangerouslyExpireAt) {
323
- fullData.dangerouslyExpireAtTTL = new Date(fullData.dangerouslyExpireAt);
324
- }
325
- else {
326
- delete fullData.dangerouslyExpireAtTTL;
327
- }
328
- return fullData;
329
- }
330
- async mocody_updateOne({ dataId, updateData, withCondition, fieldAliases, }) {
331
- this._mocody_errorHelper.mocody_helper_validateRequiredString({ dataId });
332
- const nativeId = this._mocody_getNativeMongoId(dataId);
333
- const query = { _id: nativeId };
334
- const mongo = await this._mocody_getDbInstance();
335
- const dataInDb = await mongo.findOne(query);
336
- if (!(dataInDb?.id === dataId && dataInDb.featureEntity === this._mocody_featureEntityValue)) {
337
- throw this._mocody_createGenericError("Record does not exists");
338
- }
339
- const passed = this._mocody_withConditionPassed({ item: dataInDb, withCondition });
340
- if (!passed) {
341
- throw this._mocody_createGenericError("Record with conditions does not exists");
342
- }
343
- const dataMust = this._mocody_getBaseObject({ dataId });
344
- const data = {
345
- ...dataInDb,
346
- ...updateData,
347
- ...dataMust,
348
- };
349
- mocody_utils_1.MocodyUtil.validateFieldAlias({
350
- data,
351
- fieldAliases,
352
- featureEntity: this._mocody_featureEntityValue,
353
- });
354
- const { validatedData } = await this._mocody_allHelpValidateGetValue(data);
355
- const result = await mongo.replaceOne(query, validatedData);
356
- if (!result.modifiedCount) {
357
- throw this._mocody_createGenericError(this._mocody_operationNotSuccessful);
358
- }
359
- const final = { ...validatedData };
360
- delete final._id;
361
- return final;
362
- }
363
- async mocody_prepareTransaction({ transactPrepareInfo, }) {
364
- const transactData = [];
365
- const { partitionKeyFieldName } = this._mocody_getLocalVariables();
366
- for (const item of transactPrepareInfo) {
367
- if (item.kind === "create") {
368
- const { validatedDataWithTTL } = await this._mocody_validateReady({ data: item.data });
369
- transactData.push({
370
- data: validatedDataWithTTL,
371
- partitionKeyFieldName,
372
- tableName: this._mocody_tableFullName,
373
- kind: item.kind,
374
- });
375
- }
376
- else if (item.kind === "update") {
377
- const { validatedDataWithTTL } = await this._mocody_validateReady({ data: item.data });
378
- const nativeId = this._mocody_getNativeMongoId(item.dataId);
379
- transactData.push({
380
- data: validatedDataWithTTL,
381
- partitionKeyFieldName,
382
- tableName: this._mocody_tableFullName,
383
- kind: item.kind,
384
- keyQuery: { _id: nativeId },
385
- });
386
- }
387
- else if (item.kind === "delete") {
388
- const nativeId = this._mocody_getNativeMongoId(item.dataId);
389
- transactData.push({
390
- partitionKeyFieldName,
391
- tableName: this._mocody_tableFullName,
392
- kind: item.kind,
393
- keyQuery: { _id: nativeId },
394
- });
395
- }
396
- }
397
- return transactData;
398
- }
399
- async mocody_executeTransaction({ transactInfo }) {
400
- const session = await this._mocody_mongoDb().getNewSession();
401
- try {
402
- const transactionOptions = {
403
- readPreference: new mongodb_1.ReadPreference("primary"),
404
- readConcern: new mongodb_1.ReadConcern("local"),
405
- writeConcern: new mongodb_1.WriteConcern("majority"),
406
- };
407
- await session.withTransaction(async () => {
408
- for (const item of transactInfo) {
409
- if (item.kind === "create") {
410
- const mongo = await this._mocody_getDbInstanceDefined(item.tableName);
411
- await mongo.insertOne(item.data, { session });
412
- }
413
- else if (item.kind === "update") {
414
- const mongo = await this._mocody_getDbInstanceDefined(item.tableName);
415
- const { validatedData } = await this._mocody_allHelpValidateGetValue(item.data);
416
- await mongo.replaceOne(item.keyQuery, validatedData);
417
- }
418
- else if (item.kind === "delete") {
419
- const mongo = await this._mocody_getDbInstanceDefined(item.tableName);
420
- await mongo.deleteOne(item.keyQuery);
421
- }
422
- }
423
- }, transactionOptions);
424
- await session.commitTransaction();
425
- await session.endSession();
426
- }
427
- catch (e) {
428
- await session.abortTransaction();
429
- await session.endSession();
430
- throw e;
431
- }
432
- }
433
- async mocody_getManyByIndex(paramOption) {
434
- const result = await this._mocody_getManyBySecondaryIndexPaginateBase({
435
- paramOption,
436
- canPaginate: false,
437
- enableRelationFetch: false,
438
- });
439
- if (result?.paginationResults) {
440
- return result.paginationResults;
441
- }
442
- return [];
443
- }
444
- mocody_getManyByIndexPaginate(paramOption) {
445
- return this._mocody_getManyBySecondaryIndexPaginateBase({
446
- paramOption,
447
- canPaginate: true,
448
- enableRelationFetch: false,
449
- });
450
- }
451
- async mocody_getManyWithRelation(paramOption) {
452
- const result = await this._mocody_getManyBySecondaryIndexPaginateBase({
453
- paramOption,
454
- canPaginate: false,
455
- enableRelationFetch: true,
456
- });
457
- if (result?.paginationResults) {
458
- return result.paginationResults;
459
- }
460
- return [];
461
- }
462
- async mocody_getManyWithRelationPaginate(paramOption) {
463
- return this._mocody_getManyBySecondaryIndexPaginateBase({
464
- paramOption,
465
- canPaginate: true,
466
- enableRelationFetch: true,
467
- });
468
- }
469
- async _mocody_getManyBySecondaryIndexPaginateBase({ paramOption, canPaginate, enableRelationFetch, }) {
470
- const { secondaryIndexOptions } = this._mocody_getLocalVariables();
471
- if (!secondaryIndexOptions?.length) {
472
- throw this._mocody_createGenericError("Invalid secondary index definitions");
473
- }
474
- if (!paramOption?.indexName) {
475
- throw this._mocody_createGenericError("Invalid index name input");
476
- }
477
- const secondaryIndex = secondaryIndexOptions.find((item) => {
478
- return item.indexName === paramOption.indexName;
479
- });
480
- if (!secondaryIndex) {
481
- throw this._mocody_createGenericError("Secondary index not named/defined");
482
- }
483
- const index_PartitionKeyFieldName = secondaryIndex.partitionKeyFieldName;
484
- const index_SortKeyFieldName = secondaryIndex.sortKeyFieldName;
485
- const partitionSortKeyQuery = paramOption.sortKeyQuery
486
- ? {
487
- ...{ [index_SortKeyFieldName]: paramOption.sortKeyQuery },
488
- ...{ [index_PartitionKeyFieldName]: paramOption.partitionKeyValue },
489
- }
490
- : { [index_PartitionKeyFieldName]: paramOption.partitionKeyValue };
491
- if (!enableRelationFetch) {
492
- const localVariables = this._mocody_getLocalVariables();
493
- const hasFeatureEntity = [
494
- index_PartitionKeyFieldName,
495
- index_SortKeyFieldName,
496
- ].includes(localVariables.sortKeyFieldName);
497
- paramOption.query = paramOption.query || {};
498
- if (!hasFeatureEntity) {
499
- paramOption.query = {
500
- ...paramOption.query,
501
- ...{ [localVariables.sortKeyFieldName]: localVariables.featureEntityValue },
502
- };
503
- }
504
- else if (index_PartitionKeyFieldName !== localVariables.sortKeyFieldName) {
505
- if (localVariables.sortKeyFieldName === index_SortKeyFieldName) {
506
- partitionSortKeyQuery[index_SortKeyFieldName] = { $eq: localVariables.featureEntityValue };
507
- }
508
- }
509
- }
510
- const queryDefs = {
511
- ...paramOption.query,
512
- ...partitionSortKeyQuery,
513
- };
514
- const queryDefData = this._mocody_filterQueryOperation.processQueryFilter({ queryDefs });
515
- const fieldKeys = this._mocody_getProjectionFields({
516
- fields: paramOption.fields,
517
- excludeFields: paramOption.excludeFields,
518
- });
519
- const projection = this._mocody_toMongoProjection(fieldKeys) ?? { _id: 0 };
520
- const sort01 = [];
521
- if (paramOption.sort === "desc") {
522
- sort01.push([index_PartitionKeyFieldName, -1]);
523
- sort01.push([index_SortKeyFieldName, -1]);
524
- }
525
- else {
526
- sort01.push([index_PartitionKeyFieldName, 1]);
527
- sort01.push([index_SortKeyFieldName, 1]);
528
- }
529
- let nextPageHash;
530
- const pagingOptions = {
531
- pageNo: 0,
532
- limit: constants_1.SettingDefaults.PAGE_SIZE,
533
- };
534
- const moreFindOption = {
535
- limit: undefined,
536
- skip: undefined,
537
- };
538
- if (canPaginate) {
539
- if (paramOption.limit && util_service_1.UtilService.isNumericInteger(paramOption.limit)) {
540
- pagingOptions.limit = Number(paramOption.limit);
541
- }
542
- try {
543
- const nextPageHash01 = paramOption?.pagingParams?.nextPageHash;
544
- if (nextPageHash01) {
545
- const param01 = JSON.parse(util_service_1.UtilService.decodeStringFromBase64(nextPageHash01));
546
- if (util_service_1.UtilService.isNumericInteger(param01.limit)) {
547
- pagingOptions.limit = Number(param01.limit);
548
- }
549
- if (util_service_1.UtilService.isNumericInteger(param01.pageNo)) {
550
- pagingOptions.pageNo = Number(param01.pageNo);
551
- }
552
- }
553
- }
554
- catch (error) {
555
- logging_service_1.LoggingService.log(error?.message);
556
- }
557
- const skipValue = pagingOptions.limit * (pagingOptions.pageNo || 0);
558
- if (skipValue) {
559
- moreFindOption.skip = skipValue;
560
- }
561
- moreFindOption.limit = pagingOptions.limit;
562
- }
563
- else {
564
- if (paramOption.limit && util_service_1.UtilService.isNumericInteger(paramOption.limit)) {
565
- moreFindOption.limit = Number(paramOption.limit);
566
- }
567
- }
568
- const mongo = await this._mocody_getDbInstance();
569
- const results = await mongo
570
- .find(queryDefData, {
571
- projection: projection,
572
- sort: sort01.length ? sort01 : undefined,
573
- limit: moreFindOption.limit,
574
- skip: moreFindOption.skip,
575
- })
576
- .hint(paramOption.indexName)
577
- .toArray();
578
- if (canPaginate && results.length && results.length >= pagingOptions.limit) {
579
- pagingOptions.pageNo = pagingOptions.pageNo + 1;
580
- nextPageHash = util_service_1.UtilService.encodeStringToBase64(JSON.stringify(pagingOptions));
581
- }
582
- return {
583
- paginationResults: results,
584
- nextPageHash: nextPageHash,
585
- };
586
- }
587
- async mocody_deleteById({ dataId, withCondition, }) {
588
- this._mocody_errorHelper.mocody_helper_validateRequiredString({ dataId });
589
- const db = await this._mocody_getDbInstance();
590
- const nativeId = this._mocody_getNativeMongoId(dataId);
591
- const query = { _id: nativeId };
592
- const dataInDb = await db.findOne(query);
593
- if (!(dataInDb?.id === dataId && dataInDb.featureEntity === this._mocody_featureEntityValue)) {
594
- throw this._mocody_createGenericError("Record does not exists");
595
- }
596
- const passed = this._mocody_withConditionPassed({ item: dataInDb, withCondition });
597
- if (!passed) {
598
- throw this._mocody_createGenericError("Record with conditions does not exists for deletion");
599
- }
600
- const result = await db.deleteOne(query);
601
- if (!result?.deletedCount) {
602
- throw this._mocody_createGenericError(this._mocody_operationNotSuccessful);
603
- }
604
- return dataInDb;
605
- }
606
- }
607
- exports.MongoDataOperation = MongoDataOperation;
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.MongoDataOperation = void 0;
4
+ const tslib_1 = require("tslib");
5
+ const mocody_utils_1 = require("./../helpers/mocody-utils");
6
+ const constants_1 = require("./../helpers/constants");
7
+ const util_service_1 = require("./../helpers/util-service");
8
+ const logging_service_1 = require("./../helpers/logging-service");
9
+ const model_1 = require("../model");
10
+ const joi_1 = tslib_1.__importDefault(require("joi"));
11
+ const base_schema_1 = require("../core/base-schema");
12
+ const errors_1 = require("../helpers/errors");
13
+ const base_joi_helper_1 = require("../helpers/base-joi-helper");
14
+ const mongo_filter_query_operation_1 = require("./mongo-filter-query-operation");
15
+ const mongo_table_manager_1 = require("./mongo-table-manager");
16
+ const mongodb_1 = require("mongodb");
17
+ class MongoDataOperation extends model_1.RepoModel {
18
+ constructor({ schemaDef, mongoDbInitializer, secondaryIndexOptions, featureEntityValue, baseTableName, strictRequiredFields, dataKeyGenerator, }) {
19
+ super();
20
+ Object.defineProperty(this, "_mocody_partitionKeyFieldName", {
21
+ enumerable: true,
22
+ configurable: true,
23
+ writable: true,
24
+ value: "id"
25
+ });
26
+ Object.defineProperty(this, "_mocody_sortKeyFieldName", {
27
+ enumerable: true,
28
+ configurable: true,
29
+ writable: true,
30
+ value: "featureEntity"
31
+ });
32
+ Object.defineProperty(this, "_mocody_operationNotSuccessful", {
33
+ enumerable: true,
34
+ configurable: true,
35
+ writable: true,
36
+ value: "Operation Not Successful"
37
+ });
38
+ Object.defineProperty(this, "_mocody_entityFieldsKeySet", {
39
+ enumerable: true,
40
+ configurable: true,
41
+ writable: true,
42
+ value: void 0
43
+ });
44
+ Object.defineProperty(this, "_mocody_mongoDb", {
45
+ enumerable: true,
46
+ configurable: true,
47
+ writable: true,
48
+ value: void 0
49
+ });
50
+ Object.defineProperty(this, "_mocody_dataKeyGenerator", {
51
+ enumerable: true,
52
+ configurable: true,
53
+ writable: true,
54
+ value: void 0
55
+ });
56
+ Object.defineProperty(this, "_mocody_schema", {
57
+ enumerable: true,
58
+ configurable: true,
59
+ writable: true,
60
+ value: void 0
61
+ });
62
+ Object.defineProperty(this, "_mocody_tableFullName", {
63
+ enumerable: true,
64
+ configurable: true,
65
+ writable: true,
66
+ value: void 0
67
+ });
68
+ Object.defineProperty(this, "_mocody_strictRequiredFields", {
69
+ enumerable: true,
70
+ configurable: true,
71
+ writable: true,
72
+ value: void 0
73
+ });
74
+ Object.defineProperty(this, "_mocody_featureEntityValue", {
75
+ enumerable: true,
76
+ configurable: true,
77
+ writable: true,
78
+ value: void 0
79
+ });
80
+ Object.defineProperty(this, "_mocody_secondaryIndexOptions", {
81
+ enumerable: true,
82
+ configurable: true,
83
+ writable: true,
84
+ value: void 0
85
+ });
86
+ Object.defineProperty(this, "_mocody_errorHelper", {
87
+ enumerable: true,
88
+ configurable: true,
89
+ writable: true,
90
+ value: void 0
91
+ });
92
+ Object.defineProperty(this, "_mocody_filterQueryOperation", {
93
+ enumerable: true,
94
+ configurable: true,
95
+ writable: true,
96
+ value: new mongo_filter_query_operation_1.MongoFilterQueryOperation()
97
+ });
98
+ Object.defineProperty(this, "_mocody_tableManager", {
99
+ enumerable: true,
100
+ configurable: true,
101
+ writable: true,
102
+ value: void 0
103
+ });
104
+ this._mocody_mongoDb = mongoDbInitializer;
105
+ this._mocody_dataKeyGenerator = dataKeyGenerator;
106
+ this._mocody_tableFullName = baseTableName;
107
+ this._mocody_featureEntityValue = featureEntityValue;
108
+ this._mocody_secondaryIndexOptions = secondaryIndexOptions;
109
+ this._mocody_strictRequiredFields = strictRequiredFields;
110
+ this._mocody_errorHelper = new errors_1.MocodyErrorUtils();
111
+ this._mocody_entityFieldsKeySet = new Set();
112
+ const fullSchemaMapDef = {
113
+ ...schemaDef,
114
+ ...base_schema_1.coreSchemaDefinition,
115
+ };
116
+ Object.keys(fullSchemaMapDef).forEach((key) => {
117
+ this._mocody_entityFieldsKeySet.add(key);
118
+ });
119
+ this._mocody_schema = joi_1.default.object().keys({
120
+ ...fullSchemaMapDef,
121
+ _id: joi_1.default.string().required().min(5).max(512),
122
+ });
123
+ }
124
+ mocody_tableManager() {
125
+ if (!this._mocody_tableManager) {
126
+ this._mocody_tableManager = new mongo_table_manager_1.MongoManageTable({
127
+ mongoDb: () => this._mocody_mongoDb(),
128
+ secondaryIndexOptions: this._mocody_secondaryIndexOptions,
129
+ tableFullName: this._mocody_tableFullName,
130
+ partitionKeyFieldName: this._mocody_partitionKeyFieldName,
131
+ sortKeyFieldName: this._mocody_sortKeyFieldName,
132
+ });
133
+ }
134
+ return this._mocody_tableManager;
135
+ }
136
+ _mocody_generateDynamoTableKey() {
137
+ return this._mocody_dataKeyGenerator();
138
+ }
139
+ async _mocody_getDbInstance() {
140
+ return await this._mocody_mongoDb()
141
+ .getCustomCollectionInstance(this._mocody_tableFullName);
142
+ }
143
+ async _mocody_getDbInstanceDefined(tableFullName) {
144
+ return await this._mocody_mongoDb()
145
+ .getCustomCollectionInstance(tableFullName);
146
+ }
147
+ _mocody_getLocalVariables() {
148
+ return {
149
+ partitionKeyFieldName: this._mocody_partitionKeyFieldName,
150
+ sortKeyFieldName: this._mocody_sortKeyFieldName,
151
+ featureEntityValue: this._mocody_featureEntityValue,
152
+ secondaryIndexOptions: this._mocody_secondaryIndexOptions,
153
+ strictRequiredFields: this._mocody_strictRequiredFields,
154
+ };
155
+ }
156
+ _mocody_getNativeMongoId(dataId) {
157
+ const { featureEntityValue } = this._mocody_getLocalVariables();
158
+ return [featureEntityValue, dataId].join(":");
159
+ }
160
+ _mocody_getBaseObject({ dataId }) {
161
+ const { partitionKeyFieldName, sortKeyFieldName, featureEntityValue } = this._mocody_getLocalVariables();
162
+ const dataMust = {
163
+ [partitionKeyFieldName]: dataId,
164
+ [sortKeyFieldName]: featureEntityValue,
165
+ };
166
+ return dataMust;
167
+ }
168
+ _mocody_withConditionPassed({ item, withCondition, }) {
169
+ if (item && typeof item === "object" && withCondition?.length) {
170
+ const isPassed = withCondition.every(({ field, equals }) => {
171
+ return item[field] !== undefined && item[field] === equals;
172
+ });
173
+ return isPassed;
174
+ }
175
+ return true;
176
+ }
177
+ _mocody_checkValidateMustBeAnObjectDataType(data) {
178
+ if (!data || typeof data !== "object") {
179
+ throw this._mocody_createGenericError(`Data MUST be valid object`);
180
+ }
181
+ }
182
+ _mocody_checkValidateStrictRequiredFields(onDataObj) {
183
+ this._mocody_checkValidateMustBeAnObjectDataType(onDataObj);
184
+ const { strictRequiredFields } = this._mocody_getLocalVariables();
185
+ if (strictRequiredFields?.length) {
186
+ strictRequiredFields.forEach((field) => {
187
+ if (onDataObj[field] === null || onDataObj[field] === undefined) {
188
+ throw this._mocody_createGenericError(`Strict required field: '${field}', NOT defined`);
189
+ }
190
+ });
191
+ }
192
+ }
193
+ _mocody_removeDuplicateString(list) {
194
+ return Array.from(new Set(list));
195
+ }
196
+ _mocody_getProjectionFields({ excludeFields, fields, }) {
197
+ return mocody_utils_1.MocodyUtil.getProjectionFields({
198
+ excludeFields,
199
+ fields,
200
+ entityFields: Array.from(this._mocody_entityFieldsKeySet),
201
+ });
202
+ }
203
+ _mocody_toMongoProjection(fields) {
204
+ if (fields?.length) {
205
+ const projection = {};
206
+ const uniqueFields = this._mocody_removeDuplicateString(fields);
207
+ uniqueFields.forEach((field) => {
208
+ projection[field] = 1;
209
+ });
210
+ return projection;
211
+ }
212
+ return undefined;
213
+ }
214
+ async _mocody_allHelpValidateGetValue(data) {
215
+ const { error, value } = this._mocody_schema.validate(data, {
216
+ stripUnknown: true,
217
+ });
218
+ if (error) {
219
+ const msg = (0, base_joi_helper_1.getJoiValidationErrors)(error) ?? "Validation error occured";
220
+ throw this._mocody_errorHelper.mocody_helper_createFriendlyError(msg);
221
+ }
222
+ return await Promise.resolve({ validatedData: value });
223
+ }
224
+ _mocody_createGenericError(error) {
225
+ return new errors_1.MocodyGenericError(error);
226
+ }
227
+ async mocody_getOneById({ dataId, withCondition, }) {
228
+ this._mocody_errorHelper.mocody_helper_validateRequiredString({ dataId });
229
+ const mongo = await this._mocody_getDbInstance();
230
+ const nativeId = this._mocody_getNativeMongoId(dataId);
231
+ const query = { _id: nativeId };
232
+ const dataInDb = await mongo.findOne(query, { projection: { _id: 0 } });
233
+ if (!(dataInDb?.id === dataId && dataInDb.featureEntity === this._mocody_featureEntityValue)) {
234
+ return null;
235
+ }
236
+ const passed = this._mocody_withConditionPassed({ item: dataInDb, withCondition });
237
+ if (!passed) {
238
+ return null;
239
+ }
240
+ return dataInDb;
241
+ }
242
+ async mocody_getManyByIds({ dataIds, fields, excludeFields, withCondition, }) {
243
+ const uniqueIds = this._mocody_removeDuplicateString(dataIds);
244
+ const fullUniqueIds = uniqueIds.map((id) => this._mocody_getNativeMongoId(id));
245
+ const mongo = await this._mocody_getDbInstance();
246
+ const fieldKeys = this._mocody_getProjectionFields({ fields, excludeFields });
247
+ if (withCondition?.length && fieldKeys?.length) {
248
+ withCondition.forEach((item) => {
249
+ fieldKeys.push(item.field);
250
+ });
251
+ }
252
+ const projection = this._mocody_toMongoProjection(fieldKeys);
253
+ const query = { _id: { $in: fullUniqueIds } };
254
+ const dataListInDb = await mongo.find(query, { projection }).toArray();
255
+ if (!dataListInDb?.length) {
256
+ return [];
257
+ }
258
+ const dataListInDb01 = dataListInDb.map((f) => {
259
+ return util_service_1.UtilService.deleteKeysFromObject({ dataObject: f, delKeys: ["_id"] });
260
+ });
261
+ if (withCondition?.length) {
262
+ const dataFiltered = dataListInDb01.filter((item) => {
263
+ const passed = this._mocody_withConditionPassed({ item, withCondition });
264
+ return passed;
265
+ });
266
+ return dataFiltered;
267
+ }
268
+ return dataListInDb01;
269
+ }
270
+ async mocody_formatForDump({ dataList }) {
271
+ const bulkData = [];
272
+ for (const data of dataList) {
273
+ const validatedDataWithTTL = await this.mocody_validateFormatData({ data });
274
+ bulkData.push(validatedDataWithTTL);
275
+ }
276
+ return bulkData;
277
+ }
278
+ async mocody_validateFormatData({ data }) {
279
+ const { validatedDataWithTTL } = await this._mocody_validateReady({ data });
280
+ return JSON.stringify(validatedDataWithTTL);
281
+ }
282
+ async mocody_createOne({ data, fieldAliases, }) {
283
+ const { validatedData, validatedDataWithTTL } = await this._mocody_validateReady({ data });
284
+ mocody_utils_1.MocodyUtil.validateFieldAlias({
285
+ fieldAliases,
286
+ data: validatedData,
287
+ featureEntity: this._mocody_featureEntityValue,
288
+ });
289
+ const mongo = await this._mocody_getDbInstance();
290
+ const result = await mongo.insertOne(validatedDataWithTTL);
291
+ if (!result?.acknowledged) {
292
+ throw this._mocody_createGenericError(this._mocody_operationNotSuccessful);
293
+ }
294
+ const final = { ...validatedData };
295
+ delete final._id;
296
+ return final;
297
+ }
298
+ async _mocody_validateReady({ data }) {
299
+ const { partitionKeyFieldName, featureEntityValue } = this._mocody_getLocalVariables();
300
+ let dataId = data[partitionKeyFieldName];
301
+ if (!dataId) {
302
+ dataId = this._mocody_generateDynamoTableKey();
303
+ }
304
+ if (!(dataId && typeof dataId === "string")) {
305
+ throw this._mocody_createGenericError("Invalid dataId generation");
306
+ }
307
+ const dataMust = this._mocody_getBaseObject({ dataId });
308
+ const fullData = {
309
+ ...data,
310
+ ...dataMust,
311
+ _id: this._mocody_getNativeMongoId(dataId),
312
+ };
313
+ if (fullData.featureEntity !== featureEntityValue) {
314
+ throw this._mocody_createGenericError("FeatureEntity mismatched");
315
+ }
316
+ const { validatedData } = await this._mocody_allHelpValidateGetValue(fullData);
317
+ this._mocody_checkValidateStrictRequiredFields(validatedData);
318
+ const validatedDataWithTTL = this._mocody_formatTTL(validatedData);
319
+ return { validatedData, validatedDataWithTTL };
320
+ }
321
+ _mocody_formatTTL(fullData) {
322
+ if (fullData?.dangerouslyExpireAt) {
323
+ fullData.dangerouslyExpireAtTTL = new Date(fullData.dangerouslyExpireAt);
324
+ }
325
+ else {
326
+ delete fullData.dangerouslyExpireAtTTL;
327
+ }
328
+ return fullData;
329
+ }
330
+ async mocody_updateOne({ dataId, updateData, withCondition, fieldAliases, }) {
331
+ this._mocody_errorHelper.mocody_helper_validateRequiredString({ dataId });
332
+ const nativeId = this._mocody_getNativeMongoId(dataId);
333
+ const query = { _id: nativeId };
334
+ const mongo = await this._mocody_getDbInstance();
335
+ const dataInDb = await mongo.findOne(query);
336
+ if (!(dataInDb?.id === dataId && dataInDb.featureEntity === this._mocody_featureEntityValue)) {
337
+ throw this._mocody_createGenericError("Record does not exists");
338
+ }
339
+ const passed = this._mocody_withConditionPassed({ item: dataInDb, withCondition });
340
+ if (!passed) {
341
+ throw this._mocody_createGenericError("Record with conditions does not exists");
342
+ }
343
+ const dataMust = this._mocody_getBaseObject({ dataId });
344
+ const data = {
345
+ ...dataInDb,
346
+ ...updateData,
347
+ ...dataMust,
348
+ };
349
+ mocody_utils_1.MocodyUtil.validateFieldAlias({
350
+ data,
351
+ fieldAliases,
352
+ featureEntity: this._mocody_featureEntityValue,
353
+ });
354
+ const { validatedData } = await this._mocody_allHelpValidateGetValue(data);
355
+ const result = await mongo.replaceOne(query, validatedData);
356
+ if (!result.modifiedCount) {
357
+ throw this._mocody_createGenericError(this._mocody_operationNotSuccessful);
358
+ }
359
+ const final = { ...validatedData };
360
+ delete final._id;
361
+ return final;
362
+ }
363
+ async mocody_prepareTransaction({ transactPrepareInfo, }) {
364
+ const transactData = [];
365
+ const { partitionKeyFieldName } = this._mocody_getLocalVariables();
366
+ for (const item of transactPrepareInfo) {
367
+ if (item.kind === "create") {
368
+ const { validatedDataWithTTL } = await this._mocody_validateReady({ data: item.data });
369
+ transactData.push({
370
+ data: validatedDataWithTTL,
371
+ partitionKeyFieldName,
372
+ tableName: this._mocody_tableFullName,
373
+ kind: item.kind,
374
+ });
375
+ }
376
+ else if (item.kind === "update") {
377
+ const { validatedDataWithTTL } = await this._mocody_validateReady({ data: item.data });
378
+ const nativeId = this._mocody_getNativeMongoId(item.dataId);
379
+ transactData.push({
380
+ data: validatedDataWithTTL,
381
+ partitionKeyFieldName,
382
+ tableName: this._mocody_tableFullName,
383
+ kind: item.kind,
384
+ keyQuery: { _id: nativeId },
385
+ });
386
+ }
387
+ else if (item.kind === "delete") {
388
+ const nativeId = this._mocody_getNativeMongoId(item.dataId);
389
+ transactData.push({
390
+ partitionKeyFieldName,
391
+ tableName: this._mocody_tableFullName,
392
+ kind: item.kind,
393
+ keyQuery: { _id: nativeId },
394
+ });
395
+ }
396
+ }
397
+ return transactData;
398
+ }
399
+ async mocody_executeTransaction({ transactInfo }) {
400
+ const session = await this._mocody_mongoDb().getNewSession();
401
+ try {
402
+ const transactionOptions = {
403
+ readPreference: new mongodb_1.ReadPreference("primary"),
404
+ readConcern: new mongodb_1.ReadConcern("local"),
405
+ writeConcern: new mongodb_1.WriteConcern("majority"),
406
+ };
407
+ await session.withTransaction(async () => {
408
+ for (const item of transactInfo) {
409
+ if (item.kind === "create") {
410
+ const mongo = await this._mocody_getDbInstanceDefined(item.tableName);
411
+ await mongo.insertOne(item.data, { session });
412
+ }
413
+ else if (item.kind === "update") {
414
+ const mongo = await this._mocody_getDbInstanceDefined(item.tableName);
415
+ const { validatedData } = await this._mocody_allHelpValidateGetValue(item.data);
416
+ await mongo.replaceOne(item.keyQuery, validatedData);
417
+ }
418
+ else if (item.kind === "delete") {
419
+ const mongo = await this._mocody_getDbInstanceDefined(item.tableName);
420
+ await mongo.deleteOne(item.keyQuery);
421
+ }
422
+ }
423
+ }, transactionOptions);
424
+ await session.commitTransaction();
425
+ await session.endSession();
426
+ }
427
+ catch (e) {
428
+ await session.abortTransaction();
429
+ await session.endSession();
430
+ throw e;
431
+ }
432
+ }
433
+ async mocody_getManyByIndex(paramOption) {
434
+ const result = await this._mocody_getManyBySecondaryIndexPaginateBase({
435
+ paramOption,
436
+ canPaginate: false,
437
+ enableRelationFetch: false,
438
+ });
439
+ if (result?.paginationResults) {
440
+ return result.paginationResults;
441
+ }
442
+ return [];
443
+ }
444
+ mocody_getManyByIndexPaginate(paramOption) {
445
+ return this._mocody_getManyBySecondaryIndexPaginateBase({
446
+ paramOption,
447
+ canPaginate: true,
448
+ enableRelationFetch: false,
449
+ });
450
+ }
451
+ async mocody_getManyWithRelation(paramOption) {
452
+ const result = await this._mocody_getManyBySecondaryIndexPaginateBase({
453
+ paramOption,
454
+ canPaginate: false,
455
+ enableRelationFetch: true,
456
+ });
457
+ if (result?.paginationResults) {
458
+ return result.paginationResults;
459
+ }
460
+ return [];
461
+ }
462
+ async mocody_getManyWithRelationPaginate(paramOption) {
463
+ return this._mocody_getManyBySecondaryIndexPaginateBase({
464
+ paramOption,
465
+ canPaginate: true,
466
+ enableRelationFetch: true,
467
+ });
468
+ }
469
+ async _mocody_getManyBySecondaryIndexPaginateBase({ paramOption, canPaginate, enableRelationFetch, }) {
470
+ const { secondaryIndexOptions } = this._mocody_getLocalVariables();
471
+ if (!secondaryIndexOptions?.length) {
472
+ throw this._mocody_createGenericError("Invalid secondary index definitions");
473
+ }
474
+ if (!paramOption?.indexName) {
475
+ throw this._mocody_createGenericError("Invalid index name input");
476
+ }
477
+ const secondaryIndex = secondaryIndexOptions.find((item) => {
478
+ return item.indexName === paramOption.indexName;
479
+ });
480
+ if (!secondaryIndex) {
481
+ throw this._mocody_createGenericError("Secondary index not named/defined");
482
+ }
483
+ const index_PartitionKeyFieldName = secondaryIndex.partitionKeyFieldName;
484
+ const index_SortKeyFieldName = secondaryIndex.sortKeyFieldName;
485
+ const partitionSortKeyQuery = paramOption.sortKeyQuery
486
+ ? {
487
+ ...{ [index_SortKeyFieldName]: paramOption.sortKeyQuery },
488
+ ...{ [index_PartitionKeyFieldName]: paramOption.partitionKeyValue },
489
+ }
490
+ : { [index_PartitionKeyFieldName]: paramOption.partitionKeyValue };
491
+ if (!enableRelationFetch) {
492
+ const localVariables = this._mocody_getLocalVariables();
493
+ const hasFeatureEntity = [
494
+ index_PartitionKeyFieldName,
495
+ index_SortKeyFieldName,
496
+ ].includes(localVariables.sortKeyFieldName);
497
+ paramOption.query = paramOption.query || {};
498
+ if (!hasFeatureEntity) {
499
+ paramOption.query = {
500
+ ...paramOption.query,
501
+ ...{ [localVariables.sortKeyFieldName]: localVariables.featureEntityValue },
502
+ };
503
+ }
504
+ else if (index_PartitionKeyFieldName !== localVariables.sortKeyFieldName) {
505
+ if (localVariables.sortKeyFieldName === index_SortKeyFieldName) {
506
+ partitionSortKeyQuery[index_SortKeyFieldName] = { $eq: localVariables.featureEntityValue };
507
+ }
508
+ }
509
+ }
510
+ const queryDefs = {
511
+ ...paramOption.query,
512
+ ...partitionSortKeyQuery,
513
+ };
514
+ const queryDefData = this._mocody_filterQueryOperation.processQueryFilter({ queryDefs });
515
+ const fieldKeys = this._mocody_getProjectionFields({
516
+ fields: paramOption.fields,
517
+ excludeFields: paramOption.excludeFields,
518
+ });
519
+ const projection = this._mocody_toMongoProjection(fieldKeys) ?? { _id: 0 };
520
+ const sort01 = [];
521
+ if (paramOption.sort === "desc") {
522
+ sort01.push([index_PartitionKeyFieldName, -1]);
523
+ sort01.push([index_SortKeyFieldName, -1]);
524
+ }
525
+ else {
526
+ sort01.push([index_PartitionKeyFieldName, 1]);
527
+ sort01.push([index_SortKeyFieldName, 1]);
528
+ }
529
+ let nextPageHash;
530
+ const pagingOptions = {
531
+ pageNo: 0,
532
+ limit: constants_1.SettingDefaults.PAGE_SIZE,
533
+ };
534
+ const moreFindOption = {
535
+ limit: undefined,
536
+ skip: undefined,
537
+ };
538
+ if (canPaginate) {
539
+ if (paramOption.limit && util_service_1.UtilService.isNumericInteger(paramOption.limit)) {
540
+ pagingOptions.limit = Number(paramOption.limit);
541
+ }
542
+ try {
543
+ const nextPageHash01 = paramOption?.pagingParams?.nextPageHash;
544
+ if (nextPageHash01) {
545
+ const param01 = JSON.parse(util_service_1.UtilService.decodeStringFromBase64(nextPageHash01));
546
+ if (util_service_1.UtilService.isNumericInteger(param01.limit)) {
547
+ pagingOptions.limit = Number(param01.limit);
548
+ }
549
+ if (util_service_1.UtilService.isNumericInteger(param01.pageNo)) {
550
+ pagingOptions.pageNo = Number(param01.pageNo);
551
+ }
552
+ }
553
+ }
554
+ catch (error) {
555
+ logging_service_1.LoggingService.log(error?.message);
556
+ }
557
+ const skipValue = pagingOptions.limit * (pagingOptions.pageNo || 0);
558
+ if (skipValue) {
559
+ moreFindOption.skip = skipValue;
560
+ }
561
+ moreFindOption.limit = pagingOptions.limit;
562
+ }
563
+ else {
564
+ if (paramOption.limit && util_service_1.UtilService.isNumericInteger(paramOption.limit)) {
565
+ moreFindOption.limit = Number(paramOption.limit);
566
+ }
567
+ }
568
+ const mongo = await this._mocody_getDbInstance();
569
+ const results = await mongo
570
+ .find(queryDefData, {
571
+ projection: projection,
572
+ sort: sort01.length ? sort01 : undefined,
573
+ limit: moreFindOption.limit,
574
+ skip: moreFindOption.skip,
575
+ })
576
+ .hint(paramOption.indexName)
577
+ .toArray();
578
+ if (canPaginate && results.length && results.length >= pagingOptions.limit) {
579
+ pagingOptions.pageNo = pagingOptions.pageNo + 1;
580
+ nextPageHash = util_service_1.UtilService.encodeStringToBase64(JSON.stringify(pagingOptions));
581
+ }
582
+ return {
583
+ paginationResults: results,
584
+ nextPageHash: nextPageHash,
585
+ };
586
+ }
587
+ async mocody_deleteById({ dataId, withCondition, }) {
588
+ this._mocody_errorHelper.mocody_helper_validateRequiredString({ dataId });
589
+ const db = await this._mocody_getDbInstance();
590
+ const nativeId = this._mocody_getNativeMongoId(dataId);
591
+ const query = { _id: nativeId };
592
+ const dataInDb = await db.findOne(query);
593
+ if (!(dataInDb?.id === dataId && dataInDb.featureEntity === this._mocody_featureEntityValue)) {
594
+ throw this._mocody_createGenericError("Record does not exists");
595
+ }
596
+ const passed = this._mocody_withConditionPassed({ item: dataInDb, withCondition });
597
+ if (!passed) {
598
+ throw this._mocody_createGenericError("Record with conditions does not exists for deletion");
599
+ }
600
+ const result = await db.deleteOne(query);
601
+ if (!result?.deletedCount) {
602
+ throw this._mocody_createGenericError(this._mocody_operationNotSuccessful);
603
+ }
604
+ return dataInDb;
605
+ }
606
+ }
607
+ exports.MongoDataOperation = MongoDataOperation;
608
608
  //# sourceMappingURL=mongo-data-operation.js.map