mocody 0.2.14 → 0.2.17

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