mocody 0.6.6 → 0.6.8

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