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