mocody 0.7.0 → 0.8.0

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.
package/dist/index.cjs CHANGED
@@ -36,8 +36,10 @@ __export(index_exports, {
36
36
  MocodyInitializerCouch: () => MocodyInitializerCouch,
37
37
  MocodyInitializerDynamo: () => MocodyInitializerDynamo,
38
38
  MocodyInitializerMongo: () => MocodyInitializerMongo,
39
+ MocodyInitializerPouch: () => MocodyInitializerPouch,
39
40
  MocodyUtil: () => MocodyUtil,
40
- MongoDataOperation: () => MongoDataOperation
41
+ MongoDataOperation: () => MongoDataOperation,
42
+ PouchDataOperation: () => PouchDataOperation
41
43
  });
42
44
  module.exports = __toCommonJS(index_exports);
43
45
 
@@ -456,14 +458,43 @@ var RepoModel = class {
456
458
  var import_joi2 = __toESM(require("joi"), 1);
457
459
 
458
460
  // src/helpers/base-joi-helper.ts
461
+ var fieldPlaceholderWithLabel = process.env.MOCODY_SCHEMA_VALIDATE_FIELD_PLACEHOLDER_WITH_LABEL || "";
462
+ var fieldPlaceholder = process.env.MOCODY_SCHEMA_VALIDATE_FIELD_PLACEHOLDER || "";
459
463
  function getJoiValidationErrors(err) {
460
464
  if (err?.details?.length) {
465
+ if (fieldPlaceholderWithLabel && fieldPlaceholder) {
466
+ return getJoiValidationErrorAdvanced(err);
467
+ }
461
468
  const details = JSON.parse(JSON.stringify(err.details));
462
469
  const joiData = details.map((x) => x.message.replace(new RegExp('"', "g"), ""));
463
470
  return joiData.join("; ");
464
471
  }
465
472
  return null;
466
473
  }
474
+ function getJoiValidationErrorAdvanced(err) {
475
+ if (err?.details?.length) {
476
+ const details = JSON.parse(JSON.stringify(err.details));
477
+ const joiData = details.map((issue) => {
478
+ const fieldName = issue.path.join(".");
479
+ const issueMessage = __get_val_friendly_validation_message({
480
+ fieldName,
481
+ message: issue.message.replaceAll('"', "")
482
+ });
483
+ return issueMessage;
484
+ });
485
+ return joiData.join("; ");
486
+ }
487
+ return null;
488
+ }
489
+ function __get_val_friendly_validation_message({ fieldName, message }) {
490
+ if (message?.includes(fieldPlaceholderWithLabel)) {
491
+ return message.replaceAll(fieldPlaceholderWithLabel, "");
492
+ }
493
+ if (message?.includes(fieldPlaceholder)) {
494
+ return message.replaceAll(fieldPlaceholder, fieldName);
495
+ }
496
+ return `${fieldName}: ${message}`;
497
+ }
467
498
 
468
499
  // src/core/base-schema.ts
469
500
  var import_joi = __toESM(require("joi"), 1);
@@ -4374,7 +4405,7 @@ var CouchDataOperation = class extends RepoModel {
4374
4405
  });
4375
4406
  this._mocody_schema = import_joi3.default.object().keys({
4376
4407
  ...fullSchemaMapDef,
4377
- _id: import_joi3.default.string().required().min(5).max(512)
4408
+ _id: import_joi3.default.string().required().min(4).max(512)
4378
4409
  });
4379
4410
  }
4380
4411
  mocody_tableManager() {
@@ -5403,7 +5434,7 @@ var MongoDataOperation = class extends RepoModel {
5403
5434
  });
5404
5435
  this._mocody_schema = import_joi4.default.object().keys({
5405
5436
  ...fullSchemaMapDef,
5406
- _id: import_joi4.default.string().required().min(5).max(512)
5437
+ _id: import_joi4.default.string().required().min(4).max(512)
5407
5438
  });
5408
5439
  }
5409
5440
  mocody_tableManager() {
@@ -5925,6 +5956,1227 @@ var MongoDataOperation = class extends RepoModel {
5925
5956
  return dataInDb;
5926
5957
  }
5927
5958
  };
5959
+
5960
+ // src/pouch/pouch-initializer.ts
5961
+ var import_throat4 = __toESM(require("throat"), 1);
5962
+ var import_pouchdb = __toESM(require("pouchdb"), 1);
5963
+ var import_pouchdb_find = __toESM(require("pouchdb-find"), 1);
5964
+ var concurrency4 = (0, import_throat4.default)(1);
5965
+ var MocodyInitializerPouch = class {
5966
+ _pouchInstance;
5967
+ _docMetaFieldsObJ = this.docMetaFieldsObject();
5968
+ baseConfig;
5969
+ constructor(baseConfig) {
5970
+ this.baseConfig = baseConfig;
5971
+ }
5972
+ async deleteIndex({ ddoc, name }) {
5973
+ return await this.pouch_deleteIndex({ ddoc, name });
5974
+ }
5975
+ async pouch_deleteIndex({ ddoc, name }) {
5976
+ const db01 = await this.pouch_getDbInstance();
5977
+ return await db01.deleteIndex({ ddoc, name });
5978
+ }
5979
+ async getIndexes() {
5980
+ return await this.pouch_getIndexes();
5981
+ }
5982
+ async pouch_getIndexes() {
5983
+ const db01 = await this.pouch_getDbInstance();
5984
+ return await db01.getIndexes();
5985
+ }
5986
+ async createIndex({ indexName, fields }) {
5987
+ return await this.pouch_createIndex({ indexName, fields });
5988
+ }
5989
+ async pouch_createIndex({
5990
+ indexName,
5991
+ fields,
5992
+ dbx
5993
+ }) {
5994
+ const db01 = dbx || await this.pouch_getDbInstance();
5995
+ await db01.createIndex({
5996
+ index: {
5997
+ fields,
5998
+ name: indexName,
5999
+ ddoc: indexName,
6000
+ type: "json"
6001
+ }
6002
+ });
6003
+ }
6004
+ async getById({ nativeId }) {
6005
+ const doc = await this.pouch_getById({ nativeId });
6006
+ return this.toBasicDoc_RemovePouchMeta(doc);
6007
+ }
6008
+ async pouch_getById({ nativeId }) {
6009
+ const db01 = await this.pouch_getDbInstance();
6010
+ return await db01.get(nativeId);
6011
+ }
6012
+ async getManyByIds({ nativeIds }) {
6013
+ const results = await this.pouch_getManyByIds({ nativeIds });
6014
+ const dataList = [];
6015
+ for (const item of results.rows) {
6016
+ if (item && "doc" in item && item.doc) {
6017
+ const doc01 = this.toBasicDoc_RemovePouchMeta(item.doc);
6018
+ dataList.push(doc01);
6019
+ }
6020
+ }
6021
+ return dataList;
6022
+ }
6023
+ async pouch_getManyByIds({ nativeIds }) {
6024
+ const db01 = await this.pouch_getDbInstance();
6025
+ const dataList = await db01.allDocs({
6026
+ keys: nativeIds,
6027
+ include_docs: true
6028
+ });
6029
+ return dataList;
6030
+ }
6031
+ async createDoc({ validatedData }) {
6032
+ return await this.pouch_createDoc({ validatedData });
6033
+ }
6034
+ async pouch_createDoc({ validatedData }) {
6035
+ const db01 = await this.pouch_getDbInstance();
6036
+ return await db01.put(validatedData);
6037
+ }
6038
+ async updateDoc({ docRev, validatedData }) {
6039
+ return await this.pouch_updateDoc({ validatedData, docRev });
6040
+ }
6041
+ async pouch_updateDoc({ docRev, validatedData }) {
6042
+ const db01 = await this.pouch_getDbInstance();
6043
+ return await db01.put({ ...validatedData, _rev: docRev });
6044
+ }
6045
+ async pouch_getList({ featureEntity, size, skip }) {
6046
+ const db01 = await this.pouch_getDbInstance();
6047
+ const data01 = await db01.allDocs({
6048
+ include_docs: true,
6049
+ startkey: featureEntity,
6050
+ endkey: `${featureEntity}\uFFF0`,
6051
+ inclusive_end: true,
6052
+ limit: size ?? void 0,
6053
+ skip: skip ?? void 0
6054
+ });
6055
+ return data01;
6056
+ }
6057
+ async findPartitionedDocs({ featureEntity, selector, fields, use_index, sort, limit, skip }) {
6058
+ return await this.pouch_findPartitionedDocs({
6059
+ featureEntity,
6060
+ selector,
6061
+ fields,
6062
+ use_index,
6063
+ sort,
6064
+ limit,
6065
+ skip
6066
+ });
6067
+ }
6068
+ async pouch_findPartitionedDocs({ featureEntity, selector, fields, use_index, sort, limit, skip }) {
6069
+ const db01 = await this.pouch_getDbInstance();
6070
+ const paramsQ = {
6071
+ selector: { ...selector },
6072
+ fields,
6073
+ use_index,
6074
+ sort: sort?.length ? sort : void 0,
6075
+ limit,
6076
+ skip
6077
+ };
6078
+ LoggingService.logAsString(paramsQ);
6079
+ return await db01.find(paramsQ);
6080
+ }
6081
+ async deleteById({ nativeId }) {
6082
+ const db01 = await this.pouch_deleteById({ nativeId });
6083
+ return db01;
6084
+ }
6085
+ async pouch_deleteById({ nativeId }) {
6086
+ const db01 = await this.pouch_getDbInstance();
6087
+ const doc = await this.pouch_getById({ nativeId });
6088
+ const response = await db01.remove({
6089
+ _id: doc._id,
6090
+ _rev: doc._id
6091
+ });
6092
+ return response;
6093
+ }
6094
+ async pouch_getDbInstance() {
6095
+ return await concurrency4(() => this.pouch_getDbInstanceBase());
6096
+ }
6097
+ async pouch_getDbInstanceBase() {
6098
+ if (this._pouchInstance) return this._pouchInstance;
6099
+ const {
6100
+ //
6101
+ liveSync,
6102
+ indexes,
6103
+ connType,
6104
+ localSqliteDbFilePath,
6105
+ remoteConnectionUrl
6106
+ } = this.baseConfig;
6107
+ const isLocalFirst = connType === "LOCAL_FIRST";
6108
+ const isRemoteFirst = connType === "REMOTE_FIRST";
6109
+ if (isLocalFirst) {
6110
+ if (!localSqliteDbFilePath) {
6111
+ throw new MocodyGenericError("localSqliteDbFilePath not defined");
6112
+ }
6113
+ import_pouchdb.default.plugin(import_pouchdb_find.default);
6114
+ this._pouchInstance = new import_pouchdb.default(localSqliteDbFilePath, { adapter: "nodesqlite" });
6115
+ } else {
6116
+ if (!remoteConnectionUrl) {
6117
+ throw new MocodyGenericError("couchRemoteConnectionUrl not defined");
6118
+ }
6119
+ import_pouchdb.default.plugin(import_pouchdb_find.default);
6120
+ this._pouchInstance = new import_pouchdb.default(remoteConnectionUrl);
6121
+ }
6122
+ try {
6123
+ if (indexes?.length) {
6124
+ for (const indexItem of indexes) {
6125
+ await this.pouch_createIndex({ ...indexItem, dbx: this._pouchInstance });
6126
+ }
6127
+ }
6128
+ } catch (error) {
6129
+ LoggingService.error(error);
6130
+ }
6131
+ if (isLocalFirst && remoteConnectionUrl) {
6132
+ if (liveSync) {
6133
+ this._pouchInstance.sync(remoteConnectionUrl, {
6134
+ live: true,
6135
+ retry: true
6136
+ }).on("change", (change) => {
6137
+ LoggingService.log({ replication_change: change });
6138
+ }).on("paused", (info) => {
6139
+ LoggingService.log({ replication_paused: info });
6140
+ }).on("error", (err) => {
6141
+ LoggingService.log({ replication_error: err });
6142
+ });
6143
+ } else {
6144
+ this._pouchInstance.sync(remoteConnectionUrl).on("error", (err) => {
6145
+ LoggingService.log({ replication_error: err });
6146
+ });
6147
+ }
6148
+ } else if (isRemoteFirst && localSqliteDbFilePath) {
6149
+ if (liveSync) {
6150
+ this._pouchInstance.sync(localSqliteDbFilePath, {
6151
+ live: true,
6152
+ retry: true
6153
+ }).on("change", (change) => {
6154
+ LoggingService.log({ replication_change: change });
6155
+ }).on("paused", (info) => {
6156
+ LoggingService.log({ replication_paused: info });
6157
+ }).on("error", (err) => {
6158
+ LoggingService.log({ replication_error: err });
6159
+ });
6160
+ } else {
6161
+ this._pouchInstance.sync(localSqliteDbFilePath).on("error", (err) => {
6162
+ LoggingService.log({ replication_error: err });
6163
+ });
6164
+ }
6165
+ }
6166
+ await UtilService.waitUntilMilliseconds(800);
6167
+ return await Promise.resolve(this._pouchInstance);
6168
+ }
6169
+ toBasicDoc_RemovePouchMeta(doc) {
6170
+ const cleanDoc = {};
6171
+ if (!doc) return cleanDoc;
6172
+ for (const key in doc) {
6173
+ if (Object.prototype.hasOwnProperty.call(doc, key) && !this._docMetaFieldsObJ[key]) {
6174
+ cleanDoc[key] = doc[key];
6175
+ }
6176
+ }
6177
+ return cleanDoc;
6178
+ }
6179
+ docMetaFieldsObject() {
6180
+ const docMetaFields = ["_conflicts", "_rev", "_revs_info", "_revisions", "_attachments"];
6181
+ const fld = {};
6182
+ docMetaFields.forEach((f) => {
6183
+ fld[f] = f;
6184
+ });
6185
+ return fld;
6186
+ }
6187
+ };
6188
+
6189
+ // src/pouch/pouch-data-operation.ts
6190
+ var import_joi5 = __toESM(require("joi"), 1);
6191
+
6192
+ // src/pouch/pouch-filter-query-operation.ts
6193
+ var KEY_CONDITION_MAP5 = {
6194
+ $eq: "$eq",
6195
+ $lt: "$lt",
6196
+ $lte: "$lte",
6197
+ $gt: "$gt",
6198
+ $gte: "$gte",
6199
+ $between: "",
6200
+ $beginsWith: ""
6201
+ };
6202
+ var QUERY_CONDITION_MAP_PART5 = {
6203
+ $ne: "$ne",
6204
+ $exists: "",
6205
+ $in: "",
6206
+ $nin: "",
6207
+ $contains: "",
6208
+ $notContains: "",
6209
+ $elemMatch: "",
6210
+ $nestedMatch: "",
6211
+ $nestedArrayMatch: ""
6212
+ };
6213
+ var QUERY_CONDITION_MAP_FULL5 = { ...KEY_CONDITION_MAP5, ...QUERY_CONDITION_MAP_PART5 };
6214
+ function getQueryConditionExpression3(key) {
6215
+ if (key && Object.keys(QUERY_CONDITION_MAP_FULL5).includes(key)) {
6216
+ const conditionExpr = QUERY_CONDITION_MAP_FULL5[key];
6217
+ if (conditionExpr) return conditionExpr;
6218
+ }
6219
+ return null;
6220
+ }
6221
+ function regex_pcre_beginWith2(text) {
6222
+ return `(?i)\\A${text}`;
6223
+ }
6224
+ function regex_pcre_contain2(text) {
6225
+ return `(?i)${text}`;
6226
+ }
6227
+ var PouchFilterQueryOperation = class {
6228
+ operation__filterFieldExist({ fieldName }) {
6229
+ const result = {
6230
+ [fieldName]: { $exists: true }
6231
+ };
6232
+ return result;
6233
+ }
6234
+ operation__filterFieldNotExist({ fieldName }) {
6235
+ const result = {
6236
+ [fieldName]: { $exists: false }
6237
+ };
6238
+ return result;
6239
+ }
6240
+ operation__helperFilterBasic({
6241
+ fieldName,
6242
+ val,
6243
+ conditionExpr
6244
+ }) {
6245
+ if (conditionExpr) {
6246
+ return {
6247
+ [fieldName]: { [conditionExpr]: val }
6248
+ };
6249
+ }
6250
+ const result = {
6251
+ [fieldName]: { $eq: val }
6252
+ };
6253
+ return result;
6254
+ }
6255
+ operation__filterIn({ fieldName, attrValues }) {
6256
+ const result = {
6257
+ [fieldName]: { $in: attrValues }
6258
+ };
6259
+ return result;
6260
+ }
6261
+ operation__filterNotIn({ fieldName, attrValues }) {
6262
+ const result = {
6263
+ [fieldName]: { $nin: attrValues }
6264
+ };
6265
+ return result;
6266
+ }
6267
+ operation__filterElementMatch({
6268
+ fieldName,
6269
+ attrValues
6270
+ }) {
6271
+ const result = {
6272
+ [fieldName]: {
6273
+ $elemMatch: attrValues
6274
+ }
6275
+ };
6276
+ return result;
6277
+ }
6278
+ operation__filterContains({ fieldName, term }) {
6279
+ const result = {
6280
+ [fieldName]: { $regex: regex_pcre_contain2(term) }
6281
+ };
6282
+ return result;
6283
+ }
6284
+ operation__filterNotContains({ fieldName, term }) {
6285
+ const result = {
6286
+ [fieldName]: { $not: { $regex: regex_pcre_contain2(term) } }
6287
+ };
6288
+ return result;
6289
+ }
6290
+ operation__filterBetween({ fieldName, from, to }) {
6291
+ const result = {
6292
+ [fieldName]: { $gte: from, $lte: to }
6293
+ };
6294
+ return result;
6295
+ }
6296
+ operation__filterBeginsWith({ fieldName, term }) {
6297
+ const result = {
6298
+ [fieldName]: { $regex: regex_pcre_beginWith2(term) }
6299
+ };
6300
+ return result;
6301
+ }
6302
+ operation__filterNestedMatchObject({
6303
+ fieldName,
6304
+ attrValues
6305
+ }) {
6306
+ const results = [];
6307
+ Object.entries(attrValues).forEach(([subFieldName, queryval]) => {
6308
+ let _queryValue;
6309
+ if (queryval && typeof queryval === "object") {
6310
+ _queryValue = { ...queryval };
6311
+ } else {
6312
+ _queryValue = { $eq: queryval };
6313
+ }
6314
+ Object.entries(_queryValue).forEach(([condKey, val]) => {
6315
+ const conditionKey = condKey;
6316
+ if (!Object.keys(KEY_CONDITION_MAP5).includes(conditionKey)) {
6317
+ throw MocodyErrorUtilsService.mocody_helper_createFriendlyError(
6318
+ `Invalid query key: ${conditionKey} @ NestedMatchObject`
6319
+ );
6320
+ }
6321
+ const conditionExpr = KEY_CONDITION_MAP5[conditionKey];
6322
+ if (conditionExpr) {
6323
+ const result = {
6324
+ [`${fieldName}.${subFieldName}`]: { [conditionExpr]: val }
6325
+ };
6326
+ results.push(result);
6327
+ } else {
6328
+ if (conditionKey === "$between") {
6329
+ if (!(Array.isArray(val) && val.length === 2)) {
6330
+ throw MocodyErrorUtilsService.mocody_helper_createFriendlyError("$between query must be an array of length 2");
6331
+ }
6332
+ const [fromVal, toVal] = val;
6333
+ const result = {
6334
+ [`${fieldName}.${subFieldName}`]: { $gte: fromVal, $lte: toVal }
6335
+ };
6336
+ results.push(result);
6337
+ } else if (conditionKey === "$beginsWith") {
6338
+ const result = {
6339
+ [`${fieldName}.${subFieldName}`]: { $regex: regex_pcre_beginWith2(val) }
6340
+ };
6341
+ results.push(result);
6342
+ } else {
6343
+ throw MocodyErrorUtilsService.mocody_helper_createFriendlyError(`Query key: ${conditionKey} not currently supported`);
6344
+ }
6345
+ }
6346
+ });
6347
+ });
6348
+ return results;
6349
+ }
6350
+ operation__translateAdvancedQueryOperation({
6351
+ fieldName,
6352
+ queryObject
6353
+ }) {
6354
+ const queryConditions = [];
6355
+ Object.entries(queryObject).forEach(([condKey, conditionValue]) => {
6356
+ const conditionKey = condKey;
6357
+ if (conditionValue !== void 0) {
6358
+ if (conditionKey === "$between") {
6359
+ QueryValidatorCheck.between(conditionValue);
6360
+ const _queryConditions = this.operation__filterBetween({
6361
+ fieldName,
6362
+ from: conditionValue[0],
6363
+ to: conditionValue[1]
6364
+ });
6365
+ queryConditions.push(_queryConditions);
6366
+ } else if (conditionKey === "$beginsWith") {
6367
+ QueryValidatorCheck.beginWith(conditionValue);
6368
+ const _queryConditions = this.operation__filterBeginsWith({
6369
+ fieldName,
6370
+ term: conditionValue
6371
+ });
6372
+ queryConditions.push(_queryConditions);
6373
+ } else if (conditionKey === "$contains") {
6374
+ QueryValidatorCheck.contains(conditionValue);
6375
+ const _queryConditions = this.operation__filterContains({
6376
+ fieldName,
6377
+ term: conditionValue
6378
+ });
6379
+ queryConditions.push(_queryConditions);
6380
+ } else if (conditionKey === "$notContains") {
6381
+ QueryValidatorCheck.notContains(conditionValue);
6382
+ const _queryConditions = this.operation__filterNotContains({
6383
+ fieldName,
6384
+ term: conditionValue
6385
+ });
6386
+ queryConditions.push(_queryConditions);
6387
+ } else if (conditionKey === "$in") {
6388
+ QueryValidatorCheck.in_query(conditionValue);
6389
+ const _queryConditions = this.operation__filterIn({
6390
+ fieldName,
6391
+ attrValues: conditionValue
6392
+ });
6393
+ queryConditions.push(_queryConditions);
6394
+ } else if (conditionKey === "$nin") {
6395
+ QueryValidatorCheck.notIn(conditionValue);
6396
+ const _queryConditions = this.operation__filterNotIn({
6397
+ fieldName,
6398
+ attrValues: conditionValue
6399
+ });
6400
+ queryConditions.push(_queryConditions);
6401
+ } else if (conditionKey === "$elemMatch") {
6402
+ QueryValidatorCheck.elemMatch(conditionValue);
6403
+ const _queryConditions = this.operation__filterElementMatch({
6404
+ fieldName,
6405
+ attrValues: conditionValue
6406
+ });
6407
+ queryConditions.push(_queryConditions);
6408
+ } else if (conditionKey === "$nestedMatch") {
6409
+ QueryValidatorCheck.nestedMatch(conditionValue);
6410
+ const nestedMatchConditions = this.operation__filterNestedMatchObject({
6411
+ fieldName,
6412
+ attrValues: conditionValue
6413
+ });
6414
+ if (nestedMatchConditions?.length) {
6415
+ nestedMatchConditions.forEach((_queryCondition) => {
6416
+ queryConditions.push(_queryCondition);
6417
+ });
6418
+ }
6419
+ } else if (conditionKey === "$exists") {
6420
+ QueryValidatorCheck.exists(conditionValue);
6421
+ if (String(conditionValue) === "true") {
6422
+ const _queryConditions = this.operation__filterFieldExist({
6423
+ fieldName
6424
+ });
6425
+ queryConditions.push(_queryConditions);
6426
+ } else if (String(conditionValue) === "false") {
6427
+ const _queryConditions = this.operation__filterFieldNotExist({
6428
+ fieldName
6429
+ });
6430
+ queryConditions.push(_queryConditions);
6431
+ }
6432
+ } else {
6433
+ const conditionExpr = getQueryConditionExpression3(conditionKey);
6434
+ if (conditionExpr) {
6435
+ const _queryConditions = this.operation__helperFilterBasic({
6436
+ fieldName,
6437
+ val: conditionValue,
6438
+ conditionExpr
6439
+ });
6440
+ queryConditions.push(_queryConditions);
6441
+ } else {
6442
+ QueryValidatorCheck.throwQueryNotFound(conditionKey);
6443
+ }
6444
+ }
6445
+ }
6446
+ });
6447
+ return queryConditions;
6448
+ }
6449
+ operation_translateBasicQueryOperation({ fieldName, queryObject }) {
6450
+ const _queryConditions = this.operation__helperFilterBasic({
6451
+ fieldName,
6452
+ val: queryObject
6453
+ // conditionExpr: "$eq",
6454
+ });
6455
+ return _queryConditions;
6456
+ }
6457
+ processQueryFilter({ queryDefs }) {
6458
+ let queryMainConditions = [];
6459
+ let queryAndConditions = [];
6460
+ let queryOrConditions = [];
6461
+ Object.keys(queryDefs).forEach((fieldName_Or_And) => {
6462
+ if (fieldName_Or_And === "$or") {
6463
+ const orKey = fieldName_Or_And;
6464
+ const orArray = queryDefs[orKey];
6465
+ QueryValidatorCheck.or_query(orArray);
6466
+ if (orArray && Array.isArray(orArray)) {
6467
+ orArray.forEach((orQuery) => {
6468
+ Object.keys(orQuery).forEach((fieldName) => {
6469
+ const orQueryObjectOrValue = orQuery[fieldName];
6470
+ if (orQueryObjectOrValue !== void 0) {
6471
+ if (orQueryObjectOrValue && typeof orQueryObjectOrValue === "object") {
6472
+ const _orQueryCond = this.operation__translateAdvancedQueryOperation({
6473
+ fieldName,
6474
+ queryObject: orQueryObjectOrValue
6475
+ });
6476
+ queryOrConditions = [...queryOrConditions, ..._orQueryCond];
6477
+ } else {
6478
+ const _orQueryConditions = this.operation_translateBasicQueryOperation({
6479
+ fieldName,
6480
+ queryObject: orQueryObjectOrValue
6481
+ });
6482
+ queryOrConditions = [...queryOrConditions, _orQueryConditions];
6483
+ }
6484
+ }
6485
+ });
6486
+ });
6487
+ }
6488
+ } else if (fieldName_Or_And === "$and") {
6489
+ const andKey = fieldName_Or_And;
6490
+ const andArray = queryDefs[andKey];
6491
+ QueryValidatorCheck.and_query(andArray);
6492
+ if (andArray && Array.isArray(andArray)) {
6493
+ andArray.forEach((andQuery) => {
6494
+ Object.keys(andQuery).forEach((fieldName) => {
6495
+ const andQueryObjectOrValue = andQuery[fieldName];
6496
+ if (andQueryObjectOrValue !== void 0) {
6497
+ if (andQueryObjectOrValue && typeof andQueryObjectOrValue === "object") {
6498
+ const _andQueryCond = this.operation__translateAdvancedQueryOperation({
6499
+ fieldName,
6500
+ queryObject: andQueryObjectOrValue
6501
+ });
6502
+ queryAndConditions = [...queryAndConditions, ..._andQueryCond];
6503
+ } else {
6504
+ const _andQueryConditions = this.operation_translateBasicQueryOperation({
6505
+ fieldName,
6506
+ queryObject: andQueryObjectOrValue
6507
+ });
6508
+ queryAndConditions = [...queryAndConditions, _andQueryConditions];
6509
+ }
6510
+ }
6511
+ });
6512
+ });
6513
+ }
6514
+ } else {
6515
+ if (fieldName_Or_And) {
6516
+ const fieldName2 = fieldName_Or_And;
6517
+ const queryObjectOrValue = queryDefs[fieldName2];
6518
+ if (queryObjectOrValue !== void 0) {
6519
+ if (queryObjectOrValue && typeof queryObjectOrValue === "object") {
6520
+ const _queryCond = this.operation__translateAdvancedQueryOperation({
6521
+ fieldName: fieldName2,
6522
+ queryObject: queryObjectOrValue
6523
+ });
6524
+ queryMainConditions = [...queryMainConditions, ..._queryCond];
6525
+ } else {
6526
+ const _queryConditions = this.operation_translateBasicQueryOperation({
6527
+ fieldName: fieldName2,
6528
+ queryObject: queryObjectOrValue
6529
+ });
6530
+ queryMainConditions = [...queryMainConditions, _queryConditions];
6531
+ }
6532
+ }
6533
+ }
6534
+ }
6535
+ });
6536
+ let queryAllConditions = {};
6537
+ if (queryMainConditions?.length) {
6538
+ queryMainConditions.forEach((item1) => {
6539
+ if (item1) {
6540
+ queryAllConditions = { ...queryAllConditions, ...item1 };
6541
+ }
6542
+ });
6543
+ }
6544
+ if (queryAndConditions?.length) {
6545
+ queryAllConditions.$and = queryAndConditions;
6546
+ }
6547
+ if (queryOrConditions?.length) {
6548
+ queryAllConditions.$or = queryOrConditions;
6549
+ }
6550
+ return queryAllConditions;
6551
+ }
6552
+ };
6553
+
6554
+ // src/pouch/pouch-manage-table.ts
6555
+ var PouchManageTable = class {
6556
+ partitionKeyFieldName;
6557
+ sortKeyFieldName;
6558
+ pouchDb;
6559
+ tableFullName;
6560
+ secondaryIndexOptions;
6561
+ constructor({ pouchDb, secondaryIndexOptions, tableFullName, partitionKeyFieldName, sortKeyFieldName }) {
6562
+ this.pouchDb = pouchDb;
6563
+ this.tableFullName = tableFullName;
6564
+ this.partitionKeyFieldName = partitionKeyFieldName;
6565
+ this.sortKeyFieldName = sortKeyFieldName;
6566
+ this.secondaryIndexOptions = secondaryIndexOptions;
6567
+ this._trickLinter();
6568
+ }
6569
+ _trickLinter() {
6570
+ if (this.partitionKeyFieldName && this.sortKeyFieldName && this.tableFullName) {
6571
+ }
6572
+ }
6573
+ _mocody_getInstance() {
6574
+ return this.pouchDb();
6575
+ }
6576
+ async mocody_createIndex({ indexName, fields }) {
6577
+ return await this._mocody_getInstance().createIndex({
6578
+ indexName,
6579
+ fields
6580
+ });
6581
+ }
6582
+ async mocody_clearAllIndexes() {
6583
+ const indexes = await this._mocody_getInstance().getIndexes();
6584
+ LoggingService.log({ indexes });
6585
+ if (indexes?.indexes?.length) {
6586
+ const deletedIndexes = [];
6587
+ for (const index of indexes.indexes) {
6588
+ if (index?.type !== "special") {
6589
+ deletedIndexes.push(index);
6590
+ await this._mocody_getInstance().deleteIndex({
6591
+ ddoc: index.ddoc || "",
6592
+ name: index.name
6593
+ });
6594
+ }
6595
+ }
6596
+ return {
6597
+ deletedIndexes
6598
+ };
6599
+ }
6600
+ return {
6601
+ deletedIndexes: []
6602
+ };
6603
+ }
6604
+ async mocody_getIndexes() {
6605
+ return await this._mocody_getInstance().getIndexes();
6606
+ }
6607
+ async mocody_createDefinedIndexes() {
6608
+ const results = [];
6609
+ if (this.secondaryIndexOptions?.length) {
6610
+ for (const indexOption of this.secondaryIndexOptions) {
6611
+ if (indexOption?.indexName) {
6612
+ const resultData = await this.mocody_createIndex({
6613
+ fields: [indexOption.partitionKeyFieldName, indexOption.sortKeyFieldName],
6614
+ indexName: indexOption.indexName
6615
+ });
6616
+ LoggingService.log(resultData);
6617
+ results.push(resultData);
6618
+ }
6619
+ }
6620
+ }
6621
+ return results;
6622
+ }
6623
+ };
6624
+
6625
+ // src/pouch/pouch-data-operation.ts
6626
+ var PouchDataOperation = class extends RepoModel {
6627
+ _mocody_partitionKeyFieldName = "id";
6628
+ _mocody_sortKeyFieldName = "featureEntity";
6629
+ //
6630
+ _mocody_operationNotSuccessful = "Operation Not Successful";
6631
+ _mocody_entityFieldsKeySet;
6632
+ _mocody_pouchDb;
6633
+ _mocody_dataKeyGenerator;
6634
+ _mocody_schema;
6635
+ _mocody_tableFullName;
6636
+ _mocody_strictRequiredFields;
6637
+ _mocody_featureEntityValue;
6638
+ _mocody_secondaryIndexOptions;
6639
+ _mocody_filterQueryOperation = new PouchFilterQueryOperation();
6640
+ //
6641
+ _mocody_fieldAliases;
6642
+ //
6643
+ _mocody_tableManager;
6644
+ constructor({
6645
+ schemaDef,
6646
+ pouchDbInitializer,
6647
+ secondaryIndexOptions,
6648
+ featureEntityValue,
6649
+ baseTableName,
6650
+ strictRequiredFields,
6651
+ dataKeyGenerator,
6652
+ fieldAliases
6653
+ }) {
6654
+ super();
6655
+ this._mocody_pouchDb = pouchDbInitializer;
6656
+ this._mocody_dataKeyGenerator = dataKeyGenerator;
6657
+ this._mocody_tableFullName = baseTableName;
6658
+ this._mocody_featureEntityValue = featureEntityValue;
6659
+ this._mocody_secondaryIndexOptions = secondaryIndexOptions;
6660
+ this._mocody_strictRequiredFields = strictRequiredFields;
6661
+ this._mocody_entityFieldsKeySet = /* @__PURE__ */ new Set();
6662
+ this._mocody_fieldAliases = fieldAliases;
6663
+ const fullSchemaMapDef = {
6664
+ ...schemaDef,
6665
+ ...coreSchemaDefinition
6666
+ };
6667
+ Object.keys(fullSchemaMapDef).forEach((key) => {
6668
+ this._mocody_entityFieldsKeySet.add(key);
6669
+ });
6670
+ this._mocody_schema = import_joi5.default.object().keys({
6671
+ ...fullSchemaMapDef,
6672
+ _id: import_joi5.default.string().required().min(4).max(512)
6673
+ });
6674
+ }
6675
+ mocody_tableManager() {
6676
+ if (!this._mocody_tableManager) {
6677
+ this._mocody_tableManager = new PouchManageTable({
6678
+ pouchDb: () => this._mocody_pouchDb(),
6679
+ secondaryIndexOptions: this._mocody_secondaryIndexOptions,
6680
+ tableFullName: this._mocody_tableFullName,
6681
+ partitionKeyFieldName: this._mocody_partitionKeyFieldName,
6682
+ sortKeyFieldName: this._mocody_sortKeyFieldName
6683
+ });
6684
+ }
6685
+ return this._mocody_tableManager;
6686
+ }
6687
+ _mocody_generateDynamoTableKey() {
6688
+ return this._mocody_dataKeyGenerator();
6689
+ }
6690
+ _mocody_pouchDbInstance() {
6691
+ return this._mocody_pouchDb();
6692
+ }
6693
+ _mocody_getLocalVariables() {
6694
+ return {
6695
+ partitionKeyFieldName: this._mocody_partitionKeyFieldName,
6696
+ sortKeyFieldName: this._mocody_sortKeyFieldName,
6697
+ //
6698
+ featureEntityValue: this._mocody_featureEntityValue,
6699
+ //
6700
+ secondaryIndexOptions: this._mocody_secondaryIndexOptions,
6701
+ strictRequiredFields: this._mocody_strictRequiredFields
6702
+ };
6703
+ }
6704
+ _mocody_getProjectionFields({
6705
+ excludeFields,
6706
+ fields
6707
+ }) {
6708
+ return MocodyUtil.getProjectionFields({
6709
+ excludeFields,
6710
+ fields,
6711
+ entityFields: Array.from(this._mocody_entityFieldsKeySet)
6712
+ });
6713
+ }
6714
+ _mocody_stripNonRequiredOutputData({
6715
+ dataObj,
6716
+ excludeFields
6717
+ }) {
6718
+ const returnData = {};
6719
+ if (dataObj && typeof dataObj === "object" && this._mocody_entityFieldsKeySet.size > 0) {
6720
+ Object.entries({ ...dataObj }).forEach(([key, value]) => {
6721
+ if (this._mocody_entityFieldsKeySet.has(key)) {
6722
+ if (excludeFields?.length) {
6723
+ if (!excludeFields.includes(key)) {
6724
+ returnData[key] = value;
6725
+ }
6726
+ } else {
6727
+ returnData[key] = value;
6728
+ }
6729
+ }
6730
+ });
6731
+ }
6732
+ return returnData;
6733
+ }
6734
+ _mocody_getNativePouchId(dataId) {
6735
+ const { featureEntityValue } = this._mocody_getLocalVariables();
6736
+ return [featureEntityValue, dataId].join(":");
6737
+ }
6738
+ _mocody_getBaseObject({ dataId }) {
6739
+ const { partitionKeyFieldName, sortKeyFieldName, featureEntityValue } = this._mocody_getLocalVariables();
6740
+ const dataMust = {
6741
+ [partitionKeyFieldName]: dataId,
6742
+ [sortKeyFieldName]: featureEntityValue
6743
+ };
6744
+ return dataMust;
6745
+ }
6746
+ _mocody_withConditionPassed({
6747
+ item,
6748
+ withCondition
6749
+ }) {
6750
+ if (item && typeof item === "object" && withCondition?.length) {
6751
+ const isPassed = withCondition.every(({ field, equals }) => {
6752
+ return item[field] !== void 0 && item[field] === equals;
6753
+ });
6754
+ return isPassed;
6755
+ }
6756
+ return true;
6757
+ }
6758
+ _mocody_checkValidateMustBeAnObjectDataType(data) {
6759
+ if (!data || typeof data !== "object") {
6760
+ throw this._mocody_createGenericError(`Data MUST be valid object`);
6761
+ }
6762
+ }
6763
+ _mocody_checkValidateStrictRequiredFields(onDataObj) {
6764
+ this._mocody_checkValidateMustBeAnObjectDataType(onDataObj);
6765
+ const { strictRequiredFields } = this._mocody_getLocalVariables();
6766
+ if (strictRequiredFields?.length) {
6767
+ strictRequiredFields.forEach((field) => {
6768
+ if (onDataObj[field] === null || onDataObj[field] === void 0) {
6769
+ throw this._mocody_createGenericError(`Strict required field: '${field}', NOT defined`);
6770
+ }
6771
+ });
6772
+ }
6773
+ }
6774
+ _mocody_removeDuplicateString(list) {
6775
+ return Array.from(new Set(list));
6776
+ }
6777
+ async _mocody_allHelpValidateGetValue(data) {
6778
+ const { error, value } = this._mocody_schema.validate(data, {
6779
+ stripUnknown: true
6780
+ });
6781
+ if (error) {
6782
+ const msg = getJoiValidationErrors(error) ?? "Validation error occured";
6783
+ throw MocodyErrorUtilsService.mocody_helper_createFriendlyError(msg);
6784
+ }
6785
+ const validatedData = MocodyUtil.alignFormatFieldAlias({
6786
+ data: value,
6787
+ fieldAliases: this._mocody_fieldAliases,
6788
+ featureEntity: this._mocody_featureEntityValue
6789
+ });
6790
+ MocodyUtil.validateFieldAlias({
6791
+ data: validatedData,
6792
+ fieldAliases: this._mocody_fieldAliases,
6793
+ featureEntity: this._mocody_featureEntityValue
6794
+ });
6795
+ return await Promise.resolve({ validatedData });
6796
+ }
6797
+ _mocody_createGenericError(error) {
6798
+ return new MocodyGenericError(error);
6799
+ }
6800
+ async mocody_createOne({ data }) {
6801
+ const { validatedData } = await this._mocody_validateReady({ data });
6802
+ const result = await this._mocody_pouchDbInstance().createDoc({ validatedData });
6803
+ if (!result.ok) {
6804
+ throw this._mocody_createGenericError(this._mocody_operationNotSuccessful);
6805
+ }
6806
+ return this._mocody_stripNonRequiredOutputData({ dataObj: validatedData });
6807
+ }
6808
+ async mocody_formatForDump({ dataList }) {
6809
+ const bulkData = [];
6810
+ for (const data of dataList) {
6811
+ const validatedData = await this.mocody_validateFormatData({ data });
6812
+ bulkData.push(validatedData);
6813
+ }
6814
+ return bulkData;
6815
+ }
6816
+ async mocody_validateFormatData({ data }) {
6817
+ const { validatedData } = await this._mocody_validateReady({ data });
6818
+ return JSON.stringify(validatedData);
6819
+ }
6820
+ async _mocody_validateReady({ data }) {
6821
+ const { partitionKeyFieldName, featureEntityValue } = this._mocody_getLocalVariables();
6822
+ let dataId = data[partitionKeyFieldName];
6823
+ if (!dataId) {
6824
+ dataId = this._mocody_generateDynamoTableKey();
6825
+ }
6826
+ if (!(dataId && typeof dataId === "string")) {
6827
+ throw this._mocody_createGenericError("Invalid dataId generation");
6828
+ }
6829
+ const dataMust = this._mocody_getBaseObject({ dataId });
6830
+ const fullData = {
6831
+ ...data,
6832
+ ...dataMust,
6833
+ _id: this._mocody_getNativePouchId(dataId)
6834
+ };
6835
+ if (fullData.featureEntity !== featureEntityValue) {
6836
+ throw this._mocody_createGenericError("FeatureEntity mismatched");
6837
+ }
6838
+ const { validatedData } = await this._mocody_allHelpValidateGetValue(fullData);
6839
+ this._mocody_checkValidateStrictRequiredFields(validatedData);
6840
+ return { validatedData };
6841
+ }
6842
+ async mocody_getAll({ size, skip }) {
6843
+ const data01 = await this._mocody_pouchDbInstance().pouch_getList({
6844
+ featureEntity: this._mocody_featureEntityValue,
6845
+ size,
6846
+ skip
6847
+ });
6848
+ const dataList = [];
6849
+ data01?.rows?.forEach((item) => {
6850
+ if (item?.doc?.featureEntity === this._mocody_featureEntityValue) {
6851
+ const doc = this._mocody_stripNonRequiredOutputData({ dataObj: item.doc });
6852
+ dataList.push(doc);
6853
+ }
6854
+ });
6855
+ return dataList;
6856
+ }
6857
+ async mocody_getOneById({
6858
+ dataId,
6859
+ withCondition
6860
+ }) {
6861
+ MocodyErrorUtilsService.mocody_helper_validateRequiredString({ dataId });
6862
+ const nativeId = this._mocody_getNativePouchId(dataId);
6863
+ const dataInDb = await this._mocody_pouchDbInstance().getById({ nativeId });
6864
+ if (!(dataInDb?.id === dataId && dataInDb.featureEntity === this._mocody_featureEntityValue)) {
6865
+ return null;
6866
+ }
6867
+ const passed = this._mocody_withConditionPassed({ item: dataInDb, withCondition });
6868
+ if (!passed) {
6869
+ return null;
6870
+ }
6871
+ return this._mocody_stripNonRequiredOutputData({ dataObj: dataInDb });
6872
+ }
6873
+ async mocody_updateOne({
6874
+ dataId,
6875
+ updateData,
6876
+ withCondition
6877
+ }) {
6878
+ MocodyErrorUtilsService.mocody_helper_validateRequiredString({ dataId });
6879
+ const nativeId = this._mocody_getNativePouchId(dataId);
6880
+ const dataInDb = await this._mocody_pouchDbInstance().pouch_getById({
6881
+ nativeId
6882
+ });
6883
+ if (!(dataInDb?.id === dataId && dataInDb.featureEntity === this._mocody_featureEntityValue && dataInDb._rev)) {
6884
+ throw this._mocody_createGenericError("Record does not exists");
6885
+ }
6886
+ const passed = this._mocody_withConditionPassed({ item: dataInDb, withCondition });
6887
+ if (!passed) {
6888
+ throw this._mocody_createGenericError("Update conditions NOT passed");
6889
+ }
6890
+ const dataMust = this._mocody_getBaseObject({ dataId });
6891
+ const dataInDbPlain = UtilService.convertObjectPlainObject(dataInDb);
6892
+ const neededData = this._mocody_stripNonRequiredOutputData({ dataObj: dataInDbPlain });
6893
+ const data = {
6894
+ ...neededData,
6895
+ ...updateData,
6896
+ ...dataMust,
6897
+ _id: dataInDb._id
6898
+ };
6899
+ const { validatedData } = await this._mocody_allHelpValidateGetValue(data);
6900
+ this._mocody_checkValidateStrictRequiredFields(validatedData);
6901
+ const result = await this._mocody_pouchDbInstance().updateDoc({
6902
+ validatedData,
6903
+ docRev: dataInDb._rev
6904
+ });
6905
+ if (!result.ok) {
6906
+ throw this._mocody_createGenericError(this._mocody_operationNotSuccessful);
6907
+ }
6908
+ return this._mocody_stripNonRequiredOutputData({ dataObj: validatedData });
6909
+ }
6910
+ /** Not implemented */
6911
+ async mocody_prepareTransaction({
6912
+ transactPrepareInfo
6913
+ }) {
6914
+ await Promise.resolve();
6915
+ throw new Error("Pouch:PrepareTransaction not implemented.");
6916
+ }
6917
+ /** Not implemented */
6918
+ async mocody_executeTransaction({ transactInfo }) {
6919
+ await Promise.resolve();
6920
+ throw new Error("Pouch:ExecuteTransaction not implemented.");
6921
+ }
6922
+ async mocody_getManyByIds({
6923
+ dataIds,
6924
+ fields,
6925
+ excludeFields,
6926
+ withCondition
6927
+ }) {
6928
+ const dataList = [];
6929
+ if (!dataIds?.length) {
6930
+ return dataList;
6931
+ }
6932
+ dataIds.forEach((dataId) => {
6933
+ MocodyErrorUtilsService.mocody_helper_validateRequiredString({ BatchGetDataId: dataId });
6934
+ });
6935
+ const uniqueIds = this._mocody_removeDuplicateString(dataIds);
6936
+ if (uniqueIds?.length === 1) {
6937
+ const result = await this.mocody_getOneById({
6938
+ dataId: uniqueIds[0],
6939
+ withCondition
6940
+ });
6941
+ if (result) {
6942
+ if (fields?.length) {
6943
+ const result01 = UtilService.pickFromObject({ dataObject: result, pickKeys: fields });
6944
+ dataList.push(result01);
6945
+ } else {
6946
+ dataList.push(result);
6947
+ }
6948
+ }
6949
+ return dataList;
6950
+ }
6951
+ const nativeIds = uniqueIds.map((id) => this._mocody_getNativePouchId(id));
6952
+ const dataMany = await this._mocody_pouchDbInstance().getManyByIds({
6953
+ nativeIds
6954
+ });
6955
+ const fieldKeys = this._mocody_getProjectionFields({ fields, excludeFields });
6956
+ if (withCondition?.length) {
6957
+ dataMany?.forEach((item) => {
6958
+ if (item?.featureEntity === this._mocody_featureEntityValue) {
6959
+ const passed = this._mocody_withConditionPassed({ item, withCondition });
6960
+ if (passed) {
6961
+ const k = this._mocody_stripNonRequiredOutputData({
6962
+ dataObj: item,
6963
+ excludeFields: fieldKeys
6964
+ });
6965
+ dataList.push(k);
6966
+ }
6967
+ }
6968
+ });
6969
+ } else {
6970
+ dataMany?.forEach((item) => {
6971
+ if (item?.featureEntity === this._mocody_featureEntityValue) {
6972
+ const k = this._mocody_stripNonRequiredOutputData({
6973
+ dataObj: item,
6974
+ excludeFields: fieldKeys
6975
+ });
6976
+ dataList.push(k);
6977
+ }
6978
+ });
6979
+ }
6980
+ return dataList;
6981
+ }
6982
+ async mocody_getManyByIndex(paramOption) {
6983
+ const result = await this._mocody_getManyBySecondaryIndexPaginateBase({
6984
+ paramOption,
6985
+ canPaginate: false,
6986
+ enableRelationFetch: false
6987
+ });
6988
+ if (result?.paginationResults?.length) {
6989
+ return result.paginationResults;
6990
+ }
6991
+ return [];
6992
+ }
6993
+ async mocody_getManyByIndexPaginate(paramOption) {
6994
+ return this._mocody_getManyBySecondaryIndexPaginateBase({
6995
+ paramOption,
6996
+ canPaginate: true,
6997
+ enableRelationFetch: false
6998
+ });
6999
+ }
7000
+ async mocody_getManyWithRelation(paramOption) {
7001
+ const result = await this._mocody_getManyBySecondaryIndexPaginateBase({
7002
+ paramOption,
7003
+ canPaginate: false,
7004
+ enableRelationFetch: true
7005
+ });
7006
+ if (result?.paginationResults) {
7007
+ return result.paginationResults;
7008
+ }
7009
+ return [];
7010
+ }
7011
+ async mocody_getManyWithRelationPaginate(paramOption) {
7012
+ return this._mocody_getManyBySecondaryIndexPaginateBase({
7013
+ paramOption,
7014
+ canPaginate: true,
7015
+ enableRelationFetch: true
7016
+ });
7017
+ }
7018
+ async _mocody_getManyBySecondaryIndexPaginateBase({
7019
+ paramOption,
7020
+ canPaginate,
7021
+ enableRelationFetch
7022
+ }) {
7023
+ const { secondaryIndexOptions } = this._mocody_getLocalVariables();
7024
+ if (!secondaryIndexOptions?.length) {
7025
+ throw this._mocody_createGenericError("Invalid secondary index definitions");
7026
+ }
7027
+ if (!paramOption?.indexName) {
7028
+ throw this._mocody_createGenericError("Invalid index name input");
7029
+ }
7030
+ const secondaryIndex = secondaryIndexOptions.find((item) => {
7031
+ return item.indexName === paramOption.indexName;
7032
+ });
7033
+ if (!secondaryIndex) {
7034
+ throw this._mocody_createGenericError("Secondary index not named/defined");
7035
+ }
7036
+ const index_PartitionKeyFieldName = secondaryIndex.partitionKeyFieldName;
7037
+ const index_SortKeyFieldName = secondaryIndex.sortKeyFieldName;
7038
+ const partitionSortKeyQuery = paramOption.sortKeyQuery ? {
7039
+ ...{ [index_SortKeyFieldName]: paramOption.sortKeyQuery },
7040
+ ...{ [index_PartitionKeyFieldName]: paramOption.partitionKeyValue }
7041
+ } : { [index_PartitionKeyFieldName]: paramOption.partitionKeyValue };
7042
+ if (!enableRelationFetch) {
7043
+ const localVariables = this._mocody_getLocalVariables();
7044
+ const hasFeatureEntity = [
7045
+ //
7046
+ index_PartitionKeyFieldName,
7047
+ index_SortKeyFieldName
7048
+ ].includes(localVariables.sortKeyFieldName);
7049
+ paramOption.query = paramOption.query || {};
7050
+ if (!hasFeatureEntity) {
7051
+ paramOption.query = {
7052
+ ...paramOption.query,
7053
+ ...{ [localVariables.sortKeyFieldName]: localVariables.featureEntityValue }
7054
+ };
7055
+ } else if (index_PartitionKeyFieldName !== localVariables.sortKeyFieldName) {
7056
+ if (localVariables.sortKeyFieldName === index_SortKeyFieldName) {
7057
+ partitionSortKeyQuery[index_SortKeyFieldName] = { $eq: localVariables.featureEntityValue };
7058
+ }
7059
+ }
7060
+ }
7061
+ const queryDefs = {
7062
+ ...paramOption.query,
7063
+ ...partitionSortKeyQuery
7064
+ };
7065
+ const queryDefData = this._mocody_filterQueryOperation.processQueryFilter({ queryDefs });
7066
+ const query01 = {};
7067
+ const query02 = {};
7068
+ const query03 = {};
7069
+ Object.entries(queryDefData).forEach(([key, val]) => {
7070
+ if (key === index_PartitionKeyFieldName) {
7071
+ query01[key] = val;
7072
+ } else if (key === index_SortKeyFieldName) {
7073
+ query02[key] = val;
7074
+ } else {
7075
+ query03[key] = val;
7076
+ }
7077
+ });
7078
+ const queryDefDataOrdered = { ...query01, ...query02, ...query03 };
7079
+ const sort01 = [];
7080
+ if (paramOption.sort === "desc") {
7081
+ sort01.push({ [index_PartitionKeyFieldName]: "desc" });
7082
+ sort01.push({ [index_SortKeyFieldName]: "desc" });
7083
+ } else {
7084
+ sort01.push({ [index_PartitionKeyFieldName]: "asc" });
7085
+ sort01.push({ [index_SortKeyFieldName]: "asc" });
7086
+ }
7087
+ LoggingService.log({
7088
+ queryDefDataOrdered,
7089
+ sort: sort01,
7090
+ paramOption
7091
+ });
7092
+ let projection;
7093
+ const fieldKeys = this._mocody_getProjectionFields({
7094
+ fields: paramOption.fields,
7095
+ excludeFields: paramOption.excludeFields
7096
+ });
7097
+ if (fieldKeys?.length) {
7098
+ projection = this._mocody_removeDuplicateString(fieldKeys);
7099
+ }
7100
+ let nextPageHash;
7101
+ const pagingOptions = {
7102
+ pageNo: 0,
7103
+ limit: SettingDefaults.PAGE_SIZE
7104
+ };
7105
+ const moreFindOption = {
7106
+ limit: void 0,
7107
+ skip: void 0
7108
+ };
7109
+ if (canPaginate) {
7110
+ if (paramOption.limit && UtilService.isNumericInteger(paramOption.limit)) {
7111
+ pagingOptions.limit = Number(paramOption.limit);
7112
+ }
7113
+ try {
7114
+ const nextPageHash01 = paramOption?.pagingParams?.nextPageHash;
7115
+ if (nextPageHash01) {
7116
+ const param01 = JSON.parse(UtilService.decodeStringFromBase64(nextPageHash01));
7117
+ if (param01.limit) {
7118
+ pagingOptions.limit = param01.limit;
7119
+ }
7120
+ if (param01.pageNo) {
7121
+ pagingOptions.pageNo = param01.pageNo;
7122
+ }
7123
+ }
7124
+ } catch (error) {
7125
+ LoggingService.log(error);
7126
+ }
7127
+ moreFindOption.limit = pagingOptions.limit;
7128
+ const skipValue = pagingOptions.limit * (pagingOptions.pageNo || 0);
7129
+ if (skipValue) {
7130
+ moreFindOption.skip = skipValue;
7131
+ }
7132
+ } else {
7133
+ if (paramOption.limit && UtilService.isNumericInteger(paramOption.limit)) {
7134
+ moreFindOption.limit = Number(paramOption.limit);
7135
+ }
7136
+ }
7137
+ const data = await this._mocody_pouchDbInstance().findPartitionedDocs({
7138
+ featureEntity: this._mocody_featureEntityValue,
7139
+ selector: { ...queryDefDataOrdered },
7140
+ fields: projection,
7141
+ use_index: paramOption.indexName,
7142
+ sort: sort01?.length ? sort01 : void 0,
7143
+ limit: moreFindOption.limit,
7144
+ skip: moreFindOption.skip
7145
+ });
7146
+ const results = data?.docs?.map((item) => {
7147
+ return this._mocody_stripNonRequiredOutputData({ dataObj: item });
7148
+ });
7149
+ if (canPaginate && results.length && moreFindOption.limit && results.length >= moreFindOption.limit) {
7150
+ pagingOptions.pageNo = pagingOptions.pageNo + 1;
7151
+ nextPageHash = UtilService.encodeStringToBase64(JSON.stringify(pagingOptions));
7152
+ }
7153
+ return {
7154
+ paginationResults: results,
7155
+ nextPageHash
7156
+ };
7157
+ }
7158
+ async mocody_deleteById({
7159
+ dataId,
7160
+ withCondition
7161
+ }) {
7162
+ const nativeId = this._mocody_getNativePouchId(dataId);
7163
+ const dataInDb = await this._mocody_pouchDbInstance().pouch_getById({ nativeId });
7164
+ if (!(dataInDb?.id === dataId && dataInDb.featureEntity === this._mocody_featureEntityValue)) {
7165
+ throw this._mocody_createGenericError("Record does not exists");
7166
+ }
7167
+ const passed01 = this._mocody_withConditionPassed({ item: dataInDb, withCondition });
7168
+ if (!passed01) {
7169
+ throw this._mocody_createGenericError("Record with conditions does not exists for deletion");
7170
+ }
7171
+ const result = await this._mocody_pouchDbInstance().deleteById({
7172
+ nativeId: dataInDb._id
7173
+ });
7174
+ if (!result.ok) {
7175
+ throw this._mocody_createGenericError(this._mocody_operationNotSuccessful);
7176
+ }
7177
+ return this._mocody_stripNonRequiredOutputData({ dataObj: dataInDb });
7178
+ }
7179
+ };
5928
7180
  // Annotate the CommonJS export names for ESM import in node:
5929
7181
  0 && (module.exports = {
5930
7182
  CouchDataOperation,
@@ -5933,6 +7185,8 @@ var MongoDataOperation = class extends RepoModel {
5933
7185
  MocodyInitializerCouch,
5934
7186
  MocodyInitializerDynamo,
5935
7187
  MocodyInitializerMongo,
7188
+ MocodyInitializerPouch,
5936
7189
  MocodyUtil,
5937
- MongoDataOperation
7190
+ MongoDataOperation,
7191
+ PouchDataOperation
5938
7192
  });