@infrab4a/connect 4.25.0-beta.0 → 4.25.0-beta.10

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 (72) hide show
  1. package/index.cjs.js +1057 -677
  2. package/index.esm.js +1058 -677
  3. package/package.json +1 -1
  4. package/src/domain/catalog/repositories/category.repository.d.ts +15 -4
  5. package/src/domain/catalog/repositories/product.repository.d.ts +13 -5
  6. package/src/domain/general/cacheadapter.d.ts +11 -0
  7. package/src/domain/general/index.d.ts +1 -0
  8. package/src/domain/general/models/index.d.ts +0 -1
  9. package/src/domain/general/repositories/index.d.ts +0 -1
  10. package/src/domain/generic/repository/find.repository.d.ts +4 -2
  11. package/src/domain/generic/repository/get.repository.d.ts +4 -1
  12. package/src/domain/generic/repository/types/index.d.ts +3 -2
  13. package/src/domain/generic/repository/types/repository-cache-options.type.d.ts +9 -0
  14. package/src/infra/cache/index.d.ts +1 -0
  15. package/src/infra/cache/restcache.adapter.d.ts +15 -0
  16. package/src/infra/firebase/firestore/mixins/helpers/cache-key-generator.helper.d.ts +9 -0
  17. package/src/infra/firebase/firestore/mixins/helpers/index.d.ts +1 -0
  18. package/src/infra/firebase/firestore/mixins/with-firestore.mixin.d.ts +2 -1
  19. package/src/infra/firebase/firestore/mixins/with-helpers.mixin.d.ts +1 -1
  20. package/src/infra/firebase/firestore/repositories/general/index.d.ts +0 -1
  21. package/src/infra/firebase/firestore/repositories/shop-settings/home-firestore.repository.d.ts +1 -1
  22. package/src/infra/firebase/firestore/repositories/shop-settings/shop-menu-firestore.repository.d.ts +1 -1
  23. package/src/infra/firebase/firestore/repositories/shop-settings/shop-settings-firestore.repository.d.ts +1 -1
  24. package/src/infra/firebase/firestore/repositories/shopping/buy-2-win-firestore.repository.d.ts +1 -1
  25. package/src/infra/firebase/firestore/repositories/shopping/campaign-dashboard-firestore.repository.d.ts +1 -1
  26. package/src/infra/firebase/firestore/repositories/shopping/campaign-hashtag-firestore.repository.d.ts +1 -1
  27. package/src/infra/firebase/firestore/repositories/shopping/checkout-firestore.repository.d.ts +1 -1
  28. package/src/infra/firebase/firestore/repositories/shopping/checkout-subscription-firestore.repository.d.ts +1 -1
  29. package/src/infra/firebase/firestore/repositories/shopping/coupon-firestore.repository.d.ts +1 -1
  30. package/src/infra/firebase/firestore/repositories/shopping/legacy-order-firestore.repository.d.ts +1 -1
  31. package/src/infra/firebase/firestore/repositories/shopping/order-blocked-firestore.repository.d.ts +1 -1
  32. package/src/infra/firebase/firestore/repositories/shopping/order-firestore.repository.d.ts +1 -1
  33. package/src/infra/firebase/firestore/repositories/shopping/payment-firestore.repository.d.ts +1 -1
  34. package/src/infra/firebase/firestore/repositories/shopping/subscription-plan-firestore.repository.d.ts +1 -1
  35. package/src/infra/firebase/firestore/repositories/users/lead-firestore.repository.d.ts +1 -1
  36. package/src/infra/firebase/firestore/repositories/users/subscription-edition-firestore.repository.d.ts +1 -1
  37. package/src/infra/firebase/firestore/repositories/users/subscription-firestore.repository.d.ts +1 -1
  38. package/src/infra/firebase/firestore/repositories/users/subscription-materialization-firestore.repository.d.ts +1 -1
  39. package/src/infra/firebase/firestore/repositories/users/subscription-payment-firestore.repository.d.ts +1 -1
  40. package/src/infra/firebase/firestore/repositories/users/subscription-summary-firestore.repository.d.ts +1 -1
  41. package/src/infra/firebase/firestore/repositories/users/user-address-firestore.repository.d.ts +1 -1
  42. package/src/infra/firebase/firestore/repositories/users/user-beauty-profile-firestore.repository.d.ts +1 -1
  43. package/src/infra/firebase/firestore/repositories/users/user-firestore.repository.d.ts +1 -1
  44. package/src/infra/firebase/firestore/repositories/users/user-payment-method-firestore.repository.d.ts +1 -1
  45. package/src/infra/firebase/firestore/types/firestore.repository.type.d.ts +2 -1
  46. package/src/infra/hasura-graphql/mixins/helpers/cache-key-generator.helper.d.ts +6 -0
  47. package/src/infra/hasura-graphql/mixins/helpers/index.d.ts +2 -0
  48. package/src/infra/hasura-graphql/mixins/helpers/md5-generator.helper.d.ts +4 -0
  49. package/src/infra/hasura-graphql/mixins/with-find-hasura-graphql.mixin.d.ts +22 -3
  50. package/src/infra/hasura-graphql/mixins/with-get-hasura-graphql.mixin.d.ts +6 -2
  51. package/src/infra/hasura-graphql/mixins/with-hasura-graphql.mixin.d.ts +2 -1
  52. package/src/infra/hasura-graphql/repositories/catalog/category-collection-children-hasura-graphql.repository.d.ts +1 -1
  53. package/src/infra/hasura-graphql/repositories/catalog/category-filter-hasura-graphql.repository.d.ts +1 -1
  54. package/src/infra/hasura-graphql/repositories/catalog/category-hasura-graphql.repository.d.ts +19 -7
  55. package/src/infra/hasura-graphql/repositories/catalog/category-product-hasura-graphql.repository.d.ts +1 -1
  56. package/src/infra/hasura-graphql/repositories/catalog/filter-hasura-graphql.repository.d.ts +1 -1
  57. package/src/infra/hasura-graphql/repositories/catalog/filter-option-hasura-graphql.repository.d.ts +1 -1
  58. package/src/infra/hasura-graphql/repositories/catalog/product-errors-hasura-graphql.repository.d.ts +1 -1
  59. package/src/infra/hasura-graphql/repositories/catalog/product-hasura-graphql.repository.d.ts +20 -8
  60. package/src/infra/hasura-graphql/repositories/catalog/product-review-hasura-graphql.repository.d.ts +1 -1
  61. package/src/infra/hasura-graphql/repositories/catalog/product-stock-notification-hasura-graphql.repository.d.ts +1 -1
  62. package/src/infra/hasura-graphql/repositories/catalog/variant-hasura-graphql.repository.d.ts +1 -1
  63. package/src/infra/hasura-graphql/repositories/catalog/wishlist-hasura-graphql.repository.d.ts +1 -1
  64. package/src/infra/hasura-graphql/types/graphql.repository.type.d.ts +2 -1
  65. package/src/infra/index.d.ts +1 -0
  66. package/src/domain/general/enums/index.d.ts +0 -1
  67. package/src/domain/general/enums/queue-status.enum.d.ts +0 -6
  68. package/src/domain/general/models/product-queue.d.ts +0 -14
  69. package/src/domain/general/repositories/product-queue.repository.d.ts +0 -4
  70. package/src/domain/general/types/index.d.ts +0 -1
  71. package/src/domain/general/types/queue-status.type.d.ts +0 -2
  72. package/src/infra/firebase/firestore/repositories/general/product-queue.repository.d.ts +0 -7
package/index.cjs.js CHANGED
@@ -11,6 +11,7 @@ var debug = require('debug');
11
11
  var tsCustomError = require('ts-custom-error');
12
12
  var axios = require('axios');
13
13
  var auth = require('firebase/auth');
14
+ var tsMd5 = require('ts-md5');
14
15
  var firestore = require('firebase/firestore');
15
16
  var storage = require('firebase/storage');
16
17
  var gqlQueryBuilder = require('gql-query-builder');
@@ -2558,6 +2559,7 @@ class GlampointsPaymentService {
2558
2559
  console.error('[rewards - rewardByOrder] reward request error', error.response.status, JSON.stringify(error.response.data.message), order.orderNumber);
2559
2560
  else
2560
2561
  console.log(JSON.stringify(error));
2562
+ throw new Error(`Reward errors: ${error.response.data.message}`);
2561
2563
  }
2562
2564
  }
2563
2565
  async negativateRewardByOrderId(order) {
@@ -2610,12 +2612,6 @@ class LogDocument extends BaseModel {
2610
2612
  }
2611
2613
  }
2612
2614
 
2613
- class ProductQueue extends BaseModel {
2614
- static get identifiersFields() {
2615
- return ['id'];
2616
- }
2617
- }
2618
-
2619
2615
  class Sequence extends BaseModel {
2620
2616
  static get identifiersFields() {
2621
2617
  return ['id'];
@@ -2839,6 +2835,71 @@ class AdyenCardAxiosAdapter {
2839
2835
  }
2840
2836
  }
2841
2837
 
2838
+ class RestCacheAdapter {
2839
+ constructor(config) {
2840
+ this.logger = new DebugHelper('RestCacheAdapter');
2841
+ this.client = axios__default["default"].create({
2842
+ baseURL: config.baseURL,
2843
+ headers: Object.assign(Object.assign({ 'Content-Type': 'application/json' }, (lodash.isNil(config.authToken) ? {} : { Authorization: `Bearer ${config.authToken}` })), (lodash.isNil(config.mobileApiKey) ? {} : { 'X-Mobile-API-Key': config.mobileApiKey })),
2844
+ });
2845
+ }
2846
+ async set(options) {
2847
+ try {
2848
+ const response = await this.client.post('/redis/set', {
2849
+ key: options.key,
2850
+ data: options.data,
2851
+ ex: options.expirationInSeconds,
2852
+ });
2853
+ return response.data.success;
2854
+ }
2855
+ catch (error) {
2856
+ if (error instanceof Error)
2857
+ this.logger.error(new Error(`[RestCacheAdapter] Erro ao definir cache: ${error.message}`));
2858
+ return false;
2859
+ }
2860
+ }
2861
+ async get(key) {
2862
+ try {
2863
+ const response = await this.client.post('/redis/get', {
2864
+ key,
2865
+ });
2866
+ if (response.data.success) {
2867
+ return response.data.data;
2868
+ }
2869
+ return null;
2870
+ }
2871
+ catch (error) {
2872
+ if (error instanceof Error)
2873
+ this.logger.error(new Error(`[RestCacheAdapter] Erro ao recuperar cache: ${error.message}`));
2874
+ return null;
2875
+ }
2876
+ }
2877
+ async remove(key) {
2878
+ try {
2879
+ const response = await this.client.post('/redis/del', {
2880
+ key,
2881
+ });
2882
+ return response.data.success;
2883
+ }
2884
+ catch (error) {
2885
+ if (error instanceof Error)
2886
+ this.logger.error(new Error(`[RestCacheAdapter] Erro ao remover cache: ${error.message}`));
2887
+ return false;
2888
+ }
2889
+ }
2890
+ async clear() {
2891
+ try {
2892
+ const response = await this.client.post('/redis/flushdb', {});
2893
+ return response.data.success;
2894
+ }
2895
+ catch (error) {
2896
+ if (error instanceof Error)
2897
+ this.logger.error(new Error(`[RestCacheAdapter] Erro ao limpar cache: ${error.message}`));
2898
+ return false;
2899
+ }
2900
+ }
2901
+ }
2902
+
2842
2903
  class AxiosAdapter {
2843
2904
  constructor(config) {
2844
2905
  this.config = config;
@@ -3175,6 +3236,7 @@ const withFirestore = (MixinBase) => {
3175
3236
  this.fields = options.fields;
3176
3237
  this.interceptors = options.interceptors;
3177
3238
  this.logger = DebugHelper.from(this);
3239
+ this.cache = options.cache;
3178
3240
  }
3179
3241
  collection(path) {
3180
3242
  return this.firestore.getCollection(path || this.collectionName).withConverter(this.buildModelInstance());
@@ -3221,136 +3283,378 @@ const withHelpers = (MixinBase) => {
3221
3283
  };
3222
3284
  };
3223
3285
 
3224
- const withGetFirestore = (MixinBase) => {
3225
- return class GetFirestore extends MixinBase {
3226
- async get(identifiers) {
3227
- var _a, _b, _c, _d;
3228
- const logger = this.logger.with('get');
3229
- const collectionName = this.buildCollectionPathForGet(identifiers);
3230
- const instance = this.model.toInstance(this.model.identifiersFields.reduce((acc, field) => (Object.assign(Object.assign({}, acc), { [field]: identifiers[field] })), {}));
3231
- const req = { collection: collectionName, data: identifiers };
3232
- try {
3233
- const intercepted = await ((_b = (_a = this.interceptors) === null || _a === void 0 ? void 0 : _a.request) === null || _b === void 0 ? void 0 : _b.call(_a, { instance }));
3234
- const builded = (intercepted === null || intercepted === void 0 ? void 0 : intercepted.instance) || instance;
3235
- const docRef = await this.collection(collectionName)
3236
- .getDoc(Object.values(builded.identifier).shift().toString())
3237
- .get();
3238
- const data = docRef.data();
3239
- if (lodash.isNil(data))
3240
- throw new NotFoundError(`Document '${collectionName}/${Object.values(identifiers).shift()}' not found`);
3241
- const res = ((_d = (_c = this.interceptors) === null || _c === void 0 ? void 0 : _c.response) === null || _d === void 0 ? void 0 : _d.call(_c, data, intercepted)) || data;
3242
- logger.log({ req, res });
3243
- return res;
3244
- }
3245
- catch (error) {
3246
- if (error instanceof Error)
3247
- logger.log({ req, res: error, stack: error.stack });
3248
- throw error;
3249
- }
3250
- }
3251
- buildCollectionPathForGet(identifiers) {
3252
- return this.isSubCollection(this)
3253
- ? `${this.parentRepository.collectionName}/${identifiers[this.parentIdField]}/${this.collectionName}`
3254
- : this.collectionName;
3255
- }
3256
- };
3286
+ class AttributeOptionHelper {
3287
+ }
3288
+ AttributeOptionHelper.FindByAttribute = (attributeName, fields) => {
3289
+ var _a;
3290
+ if (fields.includes(attributeName))
3291
+ return { columnName: attributeName.toString(), attributeName, to: (value) => value, from: (value) => value };
3292
+ const field = fields.find((columnOption) => lodash.isObject(columnOption) && Object.keys(columnOption).includes(attributeName.toString()));
3293
+ const fieldOption = (_a = is(field)) === null || _a === void 0 ? void 0 : _a[attributeName];
3294
+ if (lodash.isNil(fieldOption))
3295
+ return { columnName: attributeName.toString(), attributeName };
3296
+ if (Array.isArray(fieldOption))
3297
+ return { columnName: attributeName.toString(), attributeName, fields: fieldOption };
3298
+ return Object.assign({ attributeName, columnName: attributeName.toString() }, fieldOption);
3299
+ };
3300
+ AttributeOptionHelper.CheckIsColumnOption = (fieldValue) => !!(fieldValue === null || fieldValue === void 0 ? void 0 : fieldValue.columnName);
3301
+ AttributeOptionHelper.FindColumnOptionFromList = (columnName, fields) => {
3302
+ if (fields.includes(columnName))
3303
+ return { columnName, attributeName: columnName };
3304
+ const field = is(fields.find((field) => {
3305
+ if (!lodash.isObject(field))
3306
+ return false;
3307
+ const columnOption = Object.values(field).find((option) => AttributeOptionHelper.CheckIsColumnOption(option) && option.columnName === columnName ? option : {});
3308
+ return AttributeOptionHelper.CheckIsColumnOption(columnOption) && (columnOption === null || columnOption === void 0 ? void 0 : columnOption.columnName) === columnName;
3309
+ }) || {});
3310
+ const attributeName = Object.keys(field).find((fieldOptionFromList) => AttributeOptionHelper.CheckIsColumnOption(field[fieldOptionFromList]) || Array.isArray(field[fieldOptionFromList]));
3311
+ const fieldOption = field === null || field === void 0 ? void 0 : field[attributeName];
3312
+ if (Array.isArray(fieldOption))
3313
+ return { attributeName: attributeName, fields: fieldOption };
3314
+ return Object.assign({ attributeName: attributeName || columnName, columnName }, fieldOption);
3257
3315
  };
3258
3316
 
3259
- var FirestoreFieldType;
3260
- (function (FirestoreFieldType) {
3261
- FirestoreFieldType["String"] = "string";
3262
- FirestoreFieldType["Number"] = "number";
3263
- FirestoreFieldType["Boolean"] = "boolean";
3264
- FirestoreFieldType["Timestamp"] = "timestamp";
3265
- FirestoreFieldType["Array"] = "array";
3266
- FirestoreFieldType["Map"] = "map";
3267
- })(FirestoreFieldType || (FirestoreFieldType = {}));
3317
+ var HasuraGraphQLWhere;
3318
+ (function (HasuraGraphQLWhere) {
3319
+ HasuraGraphQLWhere["EQUALS"] = "_eq";
3320
+ HasuraGraphQLWhere["GT"] = "_gt";
3321
+ HasuraGraphQLWhere["GTE"] = "_gte";
3322
+ HasuraGraphQLWhere["IN"] = "_in";
3323
+ HasuraGraphQLWhere["NOTIN"] = "_nin";
3324
+ HasuraGraphQLWhere["LT"] = "_lt";
3325
+ HasuraGraphQLWhere["LTE"] = "_lte";
3326
+ HasuraGraphQLWhere["LIKE"] = "_like";
3327
+ HasuraGraphQLWhere["ILIKE"] = "_ilike";
3328
+ HasuraGraphQLWhere["NOTLIKE"] = "_nlike";
3329
+ HasuraGraphQLWhere["ISNULL"] = "_is_null";
3330
+ HasuraGraphQLWhere["ISNOTNULL"] = "_is_null";
3331
+ HasuraGraphQLWhere["JSON_CONTAINS"] = "_contains";
3332
+ HasuraGraphQLWhere["JSON_HAS_KEYS_ANY"] = "_has_keys_any";
3333
+ HasuraGraphQLWhere["IREGEX"] = "_iregex";
3334
+ HasuraGraphQLWhere["REGEX"] = "_regex";
3335
+ })(HasuraGraphQLWhere || (HasuraGraphQLWhere = {}));
3268
3336
 
3269
- const withFindFirestore = (MixinBase) => {
3270
- const checkIfIsFilterOption = (filter) => !lodash.isNil(filter === null || filter === void 0 ? void 0 : filter.operator);
3271
- const getValueFromFilter = (filter) => {
3272
- return checkIfIsFilterOption(filter) ? filter.value : filter;
3273
- };
3274
- return class FindFirestore extends MixinBase {
3275
- constructor() {
3276
- super(...arguments);
3277
- this.makeFirestoreWhere = (filter) => Object.keys(filter).reduce((queries, fieldName) => [
3278
- ...queries,
3279
- ...this.buildWhereSentence(fieldName, is(filter[fieldName])),
3280
- ], []);
3281
- this.buildWhereSentence = (fieldName, options) => {
3282
- var _a, _b, _c, _d;
3283
- if (this.isSubCollection(this) && fieldName === this.parentIdField)
3284
- return [];
3285
- const value = (options === null || options === void 0 ? void 0 : options.value) || options;
3286
- const object = {};
3287
- lodash.set(object, fieldName, value);
3288
- const plainInstance = new this.model(object).toPlain();
3289
- const firestoreFieldName = fieldName.toString().indexOf('.') > -1
3290
- ? fieldName.toString()
3291
- : Object.keys(plainInstance).find((key) => plainInstance[key]);
3292
- if ((options === null || options === void 0 ? void 0 : options.operator) === exports.Where.LIKE) {
3293
- if (Array.isArray(options === null || options === void 0 ? void 0 : options.value) &&
3294
- (((_a = this.fields) === null || _a === void 0 ? void 0 : _a[firestoreFieldName]) ===
3295
- FirestoreFieldType.Array ||
3296
- !((_b = this.fields) === null || _b === void 0 ? void 0 : _b[firestoreFieldName])))
3297
- return [[firestoreFieldName, 'array-contains-any', options.value]];
3298
- return [
3299
- [firestoreFieldName, '>=', options.value],
3300
- [firestoreFieldName, '<=', `${options.value}~`],
3301
- ];
3302
- }
3303
- if ((options === null || options === void 0 ? void 0 : options.operator) === exports.Where.IN &&
3304
- Array.isArray(options === null || options === void 0 ? void 0 : options.value) &&
3305
- (((_c = this.fields) === null || _c === void 0 ? void 0 : _c[firestoreFieldName]) ===
3306
- FirestoreFieldType.Array ||
3307
- !((_d = this.fields) === null || _d === void 0 ? void 0 : _d[firestoreFieldName])))
3308
- return [[firestoreFieldName, 'array-contains', options.value]];
3309
- if (lodash.isObject(options) && lodash.isNil(options === null || options === void 0 ? void 0 : options.operator) && lodash.isNil(options === null || options === void 0 ? void 0 : options.value)) {
3310
- return Object.keys(options).reduce((queries, key) => [
3311
- ...queries,
3312
- ...this.buildWhereSentence(`${fieldName.toString()}.${key}`, is(options)[key]),
3313
- ], []);
3314
- }
3315
- return [[firestoreFieldName, ((options === null || options === void 0 ? void 0 : options.operator) || '=='), (options === null || options === void 0 ? void 0 : options.value) || options]];
3316
- };
3317
- this.makeFirestoreOrderBy = (filters, fieldsToOrderBy) => {
3318
- const orderByKeys = Object.keys(fieldsToOrderBy || {});
3319
- if (!orderByKeys.length)
3320
- return [];
3321
- const filtersKeysWithUnordered = Object.keys(filters || {}).filter((filterKey) => !orderByKeys.includes(filterKey));
3322
- if (filtersKeysWithUnordered.length)
3323
- filtersKeysWithUnordered.forEach((filterKey) => (fieldsToOrderBy = Object.assign(Object.assign({}, (![exports.Where.EQUALS].includes(is(filters[filterKey]).operator)
3324
- ? { [filterKey]: 'asc' }
3325
- : {})), fieldsToOrderBy)));
3326
- return Object.keys(fieldsToOrderBy).map((fieldName) => [
3327
- fieldName,
3328
- fieldsToOrderBy[fieldName],
3329
- ]);
3337
+ var HasuraGraphQLColumnType;
3338
+ (function (HasuraGraphQLColumnType) {
3339
+ HasuraGraphQLColumnType["Int"] = "Int";
3340
+ HasuraGraphQLColumnType["Float"] = "Float";
3341
+ HasuraGraphQLColumnType["Boolean"] = "Boolean";
3342
+ HasuraGraphQLColumnType["String"] = "String";
3343
+ HasuraGraphQLColumnType["DateTime"] = "timestampz";
3344
+ HasuraGraphQLColumnType["Json"] = "json";
3345
+ HasuraGraphQLColumnType["Jsonb"] = "jsonb";
3346
+ HasuraGraphQLColumnType["Enum"] = "enum";
3347
+ HasuraGraphQLColumnType["Uuid"] = "uuid";
3348
+ })(HasuraGraphQLColumnType || (HasuraGraphQLColumnType = {}));
3349
+
3350
+ class FilterOptionHelper {
3351
+ }
3352
+ FilterOptionHelper.CheckIfIsFilterOption = (filter) => !lodash.isNil(filter === null || filter === void 0 ? void 0 : filter.operator);
3353
+ FilterOptionHelper.GetValueFromFilter = (filter, fieldOption) => {
3354
+ if (!FilterOptionHelper.CheckIfIsFilterOption(filter))
3355
+ return filter;
3356
+ if (filter.operator === exports.Where.ISNULL)
3357
+ return true;
3358
+ if (filter.operator === exports.Where.ISNOTNULL)
3359
+ return false;
3360
+ const converter = fieldOption.to
3361
+ ? fieldOption.to
3362
+ : (value) => filter.operator === exports.Where.LIKE && !Array.isArray(filter.value) && value.indexOf('%') < 0
3363
+ ? `%${value}%`
3364
+ : value;
3365
+ const converterResult = Array.isArray(filter.value) && !fieldOption.fields && [exports.Where.IN, exports.Where.NOTIN].includes(filter.operator)
3366
+ ? filter.value.map((fieldValue) => converter(fieldValue))
3367
+ : converter(filter.value);
3368
+ const newValue = filter.ignoreCase && !filter.ignoreAccent && !Array.isArray(filter.value) && converterResult.indexOf('%') < 0
3369
+ ? `%${converterResult}%`
3370
+ : converterResult;
3371
+ return filter.ignoreAccent && !Array.isArray(filter.value)
3372
+ ? FilterOptionHelper.buildInsensitiveSentence(newValue)
3373
+ : newValue;
3374
+ };
3375
+ FilterOptionHelper.buildInsensitiveSentence = (value) => {
3376
+ const valueWithoutAccents = FilterOptionHelper.removeAccents(value);
3377
+ let result = '';
3378
+ for (const char of valueWithoutAccents) {
3379
+ const allCharOptions = [];
3380
+ if (['a', 'e', 'i', 'o', 'u', 'c', 'A', 'E', 'I', 'O', 'U', 'C'].includes(char)) {
3381
+ const charOptions = {
3382
+ a: ['á', 'â', 'ã', 'à', 'a'],
3383
+ e: ['é', 'ê', 'ẽ', 'è', 'e'],
3384
+ i: ['í', 'î', 'ĩ', 'ì', 'i'],
3385
+ o: ['ó', 'ô', 'õ', 'ò', 'o'],
3386
+ u: ['ú', 'û', 'ũ', 'ù', 'u'],
3387
+ c: ['ç', 'c'],
3388
+ A: ['Á', 'Â', 'Ã', 'À', 'A'],
3389
+ E: ['É', 'Ê', 'Ẽ', 'È', 'E'],
3390
+ I: ['Í', 'Î', 'Ĩ', 'Ì', 'I'],
3391
+ O: ['Ó', 'Ô', 'Õ', 'Ò', 'O'],
3392
+ U: ['Ú', 'Û', 'Ũ', 'Ù', 'U'],
3393
+ C: ['Ç', 'C'],
3330
3394
  };
3395
+ allCharOptions.push(...charOptions[char]);
3396
+ result += `[${allCharOptions.join('')}]`;
3331
3397
  }
3332
- async find(find = {}) {
3333
- var _a, _b, _c, _d, _e, _f;
3334
- const logger = this.logger.with('find');
3335
- const collectionName = this.buildCollectionPathForFind(find.filters);
3336
- const collection = this.collection(collectionName);
3337
- const enableCount = (_b = (_a = find === null || find === void 0 ? void 0 : find.options) === null || _a === void 0 ? void 0 : _a.enableCount) !== null && _b !== void 0 ? _b : true;
3338
- const req = { collection: collectionName, data: find };
3398
+ else {
3399
+ result += char;
3400
+ }
3401
+ }
3402
+ return result;
3403
+ };
3404
+ FilterOptionHelper.removeAccents = (text) => {
3405
+ return text.normalize('NFD').replace(/[\u0300-\u036f]/g, '');
3406
+ };
3407
+
3408
+ class BindFilterQueryHelper {
3409
+ }
3410
+ BindFilterQueryHelper.MakeGraphQLWhere = (filter, fields) => Object.keys(filter).reduce((variables, fieldName) => {
3411
+ const columnOption = AttributeOptionHelper.FindByAttribute(fieldName, fields);
3412
+ if (!columnOption.bindFindFilter)
3413
+ return Object.assign(Object.assign({}, variables), {
3414
+ [columnOption.columnName]: BindFilterQueryHelper.BuildWhereSentence(fieldName, filter[fieldName], fields),
3415
+ });
3416
+ const builtFilter = columnOption.bindFindFilter(filter[fieldName]);
3417
+ return Object.assign(Object.assign({}, variables), Object.keys(builtFilter).reduce((variablesList, columnName) => (Object.assign(Object.assign({}, variablesList), { [columnName]: BindFilterQueryHelper.BuildWhereSentence(fieldName, builtFilter[columnName], fields) })), {}));
3418
+ }, {});
3419
+ BindFilterQueryHelper.BuildWhereSentence = (field, options, fields) => {
3420
+ const fieldSentenceOptions = AttributeOptionHelper.FindByAttribute(field, fields);
3421
+ const isNestedField = !Array.isArray(options) &&
3422
+ lodash.isObject(options) &&
3423
+ lodash.isNil(options === null || options === void 0 ? void 0 : options.operator) &&
3424
+ lodash.isNil(options === null || options === void 0 ? void 0 : options.value) &&
3425
+ lodash.isNil(fieldSentenceOptions === null || fieldSentenceOptions === void 0 ? void 0 : fieldSentenceOptions.to);
3426
+ if (isNestedField)
3427
+ return Object.keys(options).reduce((variables, key) => {
3428
+ const fieldOptions = AttributeOptionHelper.FindByAttribute(key, (fieldSentenceOptions === null || fieldSentenceOptions === void 0 ? void 0 : fieldSentenceOptions.fields) || fields);
3429
+ const columnName = fieldOptions.columnName;
3430
+ const columnFields = fieldOptions.fields;
3431
+ return Object.assign(Object.assign({}, variables), { [columnName]: BindFilterQueryHelper.BuildWhereSentence(key, is(is(options)[key]), (fieldSentenceOptions === null || fieldSentenceOptions === void 0 ? void 0 : fieldSentenceOptions.fields) || columnFields || fields) });
3432
+ }, {});
3433
+ if (!Array.isArray(options) && !lodash.isNil(fieldSentenceOptions.fields))
3434
+ return {
3435
+ [fieldSentenceOptions.fields[0]]: BindFilterQueryHelper.BuildOperatorSentence(options, fieldSentenceOptions),
3436
+ };
3437
+ if (!Array.isArray(options) && lodash.isObject(options) && !FilterOptionHelper.CheckIfIsFilterOption(options))
3438
+ options = Object.values(options)[0];
3439
+ return Array.isArray(options)
3440
+ ? options.reduce((whereSentence, option) => (Object.assign(Object.assign({}, whereSentence), BindFilterQueryHelper.BuildOperatorSentence(option, fieldSentenceOptions))), {})
3441
+ : BindFilterQueryHelper.BuildOperatorSentence(options, fieldSentenceOptions);
3442
+ };
3443
+ BindFilterQueryHelper.BuildOperatorSentence = (options, fieldOption) => ({
3444
+ [BindFilterQueryHelper.GetHasuraOperator(options, fieldOption)]: FilterOptionHelper.GetValueFromFilter(options, fieldOption),
3445
+ });
3446
+ BindFilterQueryHelper.GetHasuraOperator = (options, fieldOption) => FilterOptionHelper.CheckIfIsFilterOption(options)
3447
+ ? fieldOption.type === HasuraGraphQLColumnType.Jsonb
3448
+ ? BindFilterQueryHelper.GetHasuraJsonbOperator(options)
3449
+ : options.operator === exports.Where.LIKE && options.ignoreCase && options.ignoreAccent
3450
+ ? HasuraGraphQLWhere.IREGEX
3451
+ : options.operator === exports.Where.LIKE && options.ignoreAccent
3452
+ ? HasuraGraphQLWhere.REGEX
3453
+ : options.operator === exports.Where.LIKE && options.ignoreCase
3454
+ ? HasuraGraphQLWhere.ILIKE
3455
+ : HasuraGraphQLWhere[Object.keys(HasuraGraphQLWhere).find((graphQLOperator) => graphQLOperator ===
3456
+ Object.keys(exports.Where).find((operator) => exports.Where[operator] === (options === null || options === void 0 ? void 0 : options.operator)))]
3457
+ : HasuraGraphQLWhere.EQUALS;
3458
+ BindFilterQueryHelper.GetHasuraJsonbOperator = (options) => options.operator === exports.Where.IN
3459
+ ? HasuraGraphQLWhere.JSON_CONTAINS
3460
+ : options.operator === exports.Where.LIKE
3461
+ ? HasuraGraphQLWhere.JSON_HAS_KEYS_ANY
3462
+ : HasuraGraphQLWhere[Object.keys(HasuraGraphQLWhere).find((graphQLOperator) => graphQLOperator ===
3463
+ Object.keys(exports.Where).find((operator) => exports.Where[operator] === (options === null || options === void 0 ? void 0 : options.operator)))];
3464
+
3465
+ class CacheKeyGeneratorHelper {
3466
+ static generateCacheKeyFromIdentifiers(modelOrModelName, identifiers) {
3467
+ const sortedKeys = Object.keys(identifiers).sort();
3468
+ const keyParts = sortedKeys.map((key) => `${String(key)}:${identifiers[key]}`);
3469
+ const modelName = modelOrModelName.name.toLowerCase();
3470
+ return `${modelName}:get:${keyParts.join(':')}`;
3471
+ }
3472
+ }
3473
+
3474
+ class GraphQLFieldHelper {
3475
+ }
3476
+ GraphQLFieldHelper.CheckIsGraphQLParams = (params) => !lodash.isString(params) && Array.isArray(params) && params.length >= 0 && !!params[0].operation;
3477
+ GraphQLFieldHelper.ConvertModelFieldsToGraphQLFields = (fields) => {
3478
+ return fields === null || fields === void 0 ? void 0 : fields.map((field) => {
3479
+ if (lodash.isString(field))
3480
+ return field.toString();
3481
+ if (field === 'affected_rows')
3482
+ return field;
3483
+ const fieldName = Object.keys(field).shift();
3484
+ const fieldValue = is(field[fieldName]);
3485
+ if (Array.isArray(fieldValue))
3486
+ return { [fieldName]: GraphQLFieldHelper.ConvertModelFieldsToGraphQLFields(fieldValue) };
3487
+ if (!AttributeOptionHelper.CheckIsColumnOption(fieldValue))
3488
+ return;
3489
+ const isNestedField = !!fieldValue.fields;
3490
+ if (isNestedField)
3491
+ return GraphQLFieldHelper.ConvertNestedFieldsToGraphQLFields(fieldName, fieldValue);
3492
+ return fieldValue.columnName;
3493
+ }).filter((field) => !!field);
3494
+ };
3495
+ GraphQLFieldHelper.ConvertFieldValueFrom = (data, fields) => Object.keys(data).reduce((result, columnName) => {
3496
+ const { attributeName, fields: attributeFields, from, } = AttributeOptionHelper.FindColumnOptionFromList(columnName, fields);
3497
+ if (!!attributeFields && Array.isArray(attributeFields)) {
3498
+ if (Array.isArray(data[columnName]))
3499
+ return Object.assign(Object.assign({}, result), { [attributeName]: from
3500
+ ? from(data[columnName], data)
3501
+ : is(data[columnName]).map((value) => GraphQLFieldHelper.ConvertFieldValueFrom(is(value), attributeFields)) });
3502
+ if (lodash.isObject(data[columnName]))
3503
+ return Object.assign(Object.assign({}, result), { [attributeName]: !!from
3504
+ ? from(data[columnName])
3505
+ : GraphQLFieldHelper.ConvertFieldValueFrom(is(data[columnName]), attributeFields) });
3506
+ }
3507
+ if (!!from)
3508
+ return Object.assign(Object.assign({}, result), { [attributeName]: from(data[columnName], data) });
3509
+ return Object.assign(Object.assign({}, result), { [attributeName]: lodash.isString(data[columnName]) ? parseDateTime(data[columnName].toString()) : data[columnName] });
3510
+ }, {});
3511
+ GraphQLFieldHelper.ConvertFieldValueTo = (instance, fields, update = false) => {
3512
+ var _a;
3513
+ const data = ((_a = instance.toPlain) === null || _a === void 0 ? void 0 : _a.call(instance)) || instance;
3514
+ return Object.keys(data).reduce((result, attributeName) => {
3515
+ const { columnName, fields: attributeFields, foreignKeyColumn, to, bindPersistData, } = AttributeOptionHelper.FindByAttribute(attributeName, fields);
3516
+ if (bindPersistData)
3517
+ return Object.assign(Object.assign({}, result), bindPersistData(data[attributeName], instance));
3518
+ if (lodash.isNil(columnName))
3519
+ return result;
3520
+ if (!!foreignKeyColumn &&
3521
+ !lodash.isEmpty(foreignKeyColumn) &&
3522
+ !Object.keys(foreignKeyColumn).filter((key) => { var _a; return !((_a = is(data[attributeName])) === null || _a === void 0 ? void 0 : _a[key]); }).length)
3523
+ return Object.keys(foreignKeyColumn).reduce((object, current) => {
3524
+ var _a;
3525
+ const { columnName: foreignColumnName } = AttributeOptionHelper.FindByAttribute(foreignKeyColumn[current], fields);
3526
+ return Object.assign(Object.assign({}, object), { [foreignColumnName]: (_a = data[attributeName]) === null || _a === void 0 ? void 0 : _a[current] });
3527
+ }, Object.assign({}, result));
3528
+ if (update &&
3529
+ lodash.isObject(data[attributeName]) &&
3530
+ !lodash.isNil(attributeFields) &&
3531
+ !lodash.isDate(data[attributeName]))
3532
+ return result;
3533
+ if (!!columnName &&
3534
+ Array.isArray(attributeFields) &&
3535
+ lodash.isObject(data[attributeName])) {
3536
+ const converted = !lodash.isNil(columnName) && to
3537
+ ? to(instance[attributeName], instance)
3538
+ : data[attributeName];
3539
+ return Object.assign(Object.assign({}, result), (converted !== undefined
3540
+ ? {
3541
+ [columnName]: {
3542
+ data: instance[attributeName] instanceof BaseModel
3543
+ ? GraphQLFieldHelper.ConvertFieldValueTo(data[attributeName], attributeFields)
3544
+ : converted,
3545
+ },
3546
+ }
3547
+ : {}));
3548
+ }
3549
+ if (!!to)
3550
+ return Object.assign(Object.assign({}, result), { [columnName]: to(instance[attributeName], instance) });
3551
+ return Object.assign(Object.assign({}, result), { [columnName]: data[attributeName] });
3552
+ }, {});
3553
+ };
3554
+ GraphQLFieldHelper.ConvertNestedFieldsToGraphQLFields = (fieldName, fieldValue) => {
3555
+ const hasCustomFilters = !!fieldValue.filters;
3556
+ if (hasCustomFilters)
3557
+ return {
3558
+ operation: fieldValue.columnName || fieldName,
3559
+ fields: GraphQLFieldHelper.ConvertModelFieldsToGraphQLFields(fieldValue.fields),
3560
+ variables: {
3561
+ [`${fieldValue.columnName}_where`]: {
3562
+ name: 'where',
3563
+ type: fieldValue.filters.filterType,
3564
+ value: BindFilterQueryHelper.MakeGraphQLWhere(fieldValue.filters.filters, fieldValue.fields),
3565
+ required: true,
3566
+ },
3567
+ },
3568
+ };
3569
+ return {
3570
+ [fieldValue.columnName || fieldName]: GraphQLFieldHelper.ConvertModelFieldsToGraphQLFields(fieldValue.fields),
3571
+ };
3572
+ };
3573
+
3574
+ class MD5GeneratorHelper {
3575
+ static generateMD5(data) {
3576
+ if (data === null || data === undefined)
3577
+ return tsMd5.Md5.hashStr('null');
3578
+ const normalizedData = this.normalizeData(data);
3579
+ const jsonString = JSON.stringify(normalizedData);
3580
+ return tsMd5.Md5.hashStr(jsonString);
3581
+ }
3582
+ static normalizeData(data, depth = 0, maxDepth = 100) {
3583
+ if (depth > maxDepth)
3584
+ return '[MAX_DEPTH_REACHED]';
3585
+ if (data === null || data === undefined)
3586
+ return null;
3587
+ if (typeof data !== 'object')
3588
+ return data;
3589
+ if (Array.isArray(data))
3590
+ return data
3591
+ .map((item) => this.normalizeData(item, depth + 1, maxDepth))
3592
+ .sort((a, b) => {
3593
+ const strA = typeof a === 'object' && a !== null ? JSON.stringify(a) : String(a);
3594
+ const strB = typeof b === 'object' && b !== null ? JSON.stringify(b) : String(b);
3595
+ return strA.localeCompare(strB);
3596
+ });
3597
+ const sortedObj = {};
3598
+ const keys = Object.keys(data).sort();
3599
+ keys.forEach((key) => {
3600
+ const value = data[key];
3601
+ sortedObj[key] = this.normalizeData(value, depth + 1, maxDepth);
3602
+ });
3603
+ return sortedObj;
3604
+ }
3605
+ }
3606
+
3607
+ class FirestoreCacheKeyGeneratorHelper {
3608
+ static generateGetCacheKey(model, identifiers) {
3609
+ const sortedEntries = Object.entries(identifiers).sort(([keyA], [keyB]) => keyA.localeCompare(keyB));
3610
+ const keyParts = [];
3611
+ for (const [key, value] of sortedEntries) {
3612
+ keyParts.push(`${key}:${value}`);
3613
+ }
3614
+ return `${model.name.toLowerCase()}:get:${keyParts.join(':')}`;
3615
+ }
3616
+ static generateFindCacheKey(model, findParams) {
3617
+ const md5 = MD5GeneratorHelper.generateMD5(findParams);
3618
+ return `${model.name.toLowerCase()}:find:${md5}`;
3619
+ }
3620
+ }
3621
+
3622
+ const withGetFirestore = (MixinBase) => {
3623
+ return class GetFirestore extends MixinBase {
3624
+ async get(identifiers, options) {
3625
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j;
3626
+ const logger = this.logger.with('get');
3627
+ const collectionName = this.buildCollectionPathForGet(identifiers);
3628
+ const instance = this.model.toInstance(this.model.identifiersFields.reduce((acc, field) => (Object.assign(Object.assign({}, acc), { [field]: identifiers[field] })), {}));
3629
+ const req = { collection: collectionName, data: identifiers };
3630
+ if (((_a = this.cache) === null || _a === void 0 ? void 0 : _a.cacheAdapter) && ((_b = options === null || options === void 0 ? void 0 : options.cache) === null || _b === void 0 ? void 0 : _b.enabled) !== false) {
3631
+ const cacheKey = FirestoreCacheKeyGeneratorHelper.generateGetCacheKey(this.model, identifiers);
3632
+ const cachedData = await this.cache.cacheAdapter.get(cacheKey);
3633
+ if (cachedData) {
3634
+ logger.log({ req, res: 'Dados recuperados do cache', cacheKey });
3635
+ return this.model.toInstance(JSON.parse(cachedData));
3636
+ }
3637
+ }
3339
3638
  try {
3340
- const intercepted = await ((_d = (_c = this.interceptors) === null || _c === void 0 ? void 0 : _c.request) === null || _d === void 0 ? void 0 : _d.call(_c, { find }));
3341
- const { fields, filters, limits, orderBy } = (intercepted === null || intercepted === void 0 ? void 0 : intercepted.find) || find;
3342
- const queries = this.makeFirestoreWhere(filters || {});
3343
- const ordination = this.makeFirestoreOrderBy(filters, orderBy);
3344
- const offsets = await this.defineLimits(filters, limits);
3345
- const docs = await queries
3346
- .reduce((collection, where) => collection.where(...where), ordination.reduce((collection, ordination) => collection.order(...ordination), offsets.reduce((collection, offset) => collection[offset[0]](offset[1]), collection)))
3347
- .getDocs();
3348
- const data = docs.docs.map((doc) => doc.data());
3349
- const res = {
3350
- data: (await ((_f = (_e = this.interceptors) === null || _e === void 0 ? void 0 : _e.response) === null || _f === void 0 ? void 0 : _f.call(_e, data, intercepted))) || data,
3351
- count: enableCount ? this.calculateCount(data, limits) : Infinity,
3352
- };
3353
- logger.log({ req, queries, ordination, offsets, res });
3639
+ const intercepted = await ((_d = (_c = this.interceptors) === null || _c === void 0 ? void 0 : _c.request) === null || _d === void 0 ? void 0 : _d.call(_c, { instance }));
3640
+ const builded = (intercepted === null || intercepted === void 0 ? void 0 : intercepted.instance) || instance;
3641
+ const docRef = await this.collection(collectionName)
3642
+ .getDoc(Object.values(builded.identifier).shift().toString())
3643
+ .get();
3644
+ const data = docRef.data();
3645
+ if (lodash.isNil(data))
3646
+ throw new NotFoundError(`Document '${collectionName}/${Object.values(identifiers).shift()}' not found`);
3647
+ const res = (await ((_f = (_e = this.interceptors) === null || _e === void 0 ? void 0 : _e.response) === null || _f === void 0 ? void 0 : _f.call(_e, data, intercepted))) || data;
3648
+ logger.log({ req, res });
3649
+ if (((_g = this.cache) === null || _g === void 0 ? void 0 : _g.cacheAdapter) && ((_h = options === null || options === void 0 ? void 0 : options.cache) === null || _h === void 0 ? void 0 : _h.enabled) !== false) {
3650
+ const cacheKey = FirestoreCacheKeyGeneratorHelper.generateGetCacheKey(this.model, identifiers);
3651
+ await this.cache.cacheAdapter.set({
3652
+ key: cacheKey,
3653
+ data: JSON.stringify((res === null || res === void 0 ? void 0 : res.toPlain()) || res),
3654
+ expirationInSeconds: ((_j = options === null || options === void 0 ? void 0 : options.cache) === null || _j === void 0 ? void 0 : _j.ttl) || this.cache.ttlDefault,
3655
+ });
3656
+ logger.log({ req, message: 'Dados salvos no cache', cacheKey });
3657
+ }
3354
3658
  return res;
3355
3659
  }
3356
3660
  catch (error) {
@@ -3359,50 +3663,181 @@ const withFindFirestore = (MixinBase) => {
3359
3663
  throw error;
3360
3664
  }
3361
3665
  }
3362
- buildCollectionPathForFind(filters) {
3363
- if (!this.isSubCollection(this))
3364
- return this.collectionName;
3365
- const parentIdField = this.parentIdField;
3366
- const parentId = getValueFromFilter(filters === null || filters === void 0 ? void 0 : filters[parentIdField]);
3367
- return `${this.parentRepository.collectionName}/${parentId}/${this.collectionName}`;
3368
- }
3369
- async defineLimits(filters, limits) {
3370
- var _a;
3371
- const queries = [];
3372
- if (limits === null || limits === void 0 ? void 0 : limits.offset) {
3373
- if (this.model.isModel(limits.offset))
3374
- queries.push([
3375
- 'fromStartAfter',
3376
- await this.collection(this.buildCollectionPathForFind(filters))
3377
- .getDoc((_a = Object.values(limits.offset.identifier).shift()) === null || _a === void 0 ? void 0 : _a.toString())
3378
- .get(),
3379
- ]);
3380
- else if (lodash.isNumber(limits.offset) || lodash.isString(limits.offset)) {
3381
- queries.push(['fromStartAt', limits.offset]);
3382
- }
3383
- }
3384
- if (limits === null || limits === void 0 ? void 0 : limits.limit)
3385
- queries.push(['limit', limits.limit]);
3386
- return queries;
3387
- }
3388
- calculateCount(data, limits) {
3389
- if (data.length <= 0)
3390
- return 0;
3391
- if (data.length < (limits === null || limits === void 0 ? void 0 : limits.limit))
3392
- return data.length;
3393
- return Infinity;
3666
+ buildCollectionPathForGet(identifiers) {
3667
+ return this.isSubCollection(this)
3668
+ ? `${this.parentRepository.collectionName}/${identifiers[this.parentIdField]}/${this.collectionName}`
3669
+ : this.collectionName;
3394
3670
  }
3395
3671
  };
3396
3672
  };
3397
3673
 
3398
- const withCreateFirestore = (MixinBase) => {
3399
- return class CreateFirestore extends MixinBase {
3400
- async create(data) {
3401
- var _a, _b, _c, _d;
3402
- const logger = this.logger.with('create');
3403
- const instance = this.model.toInstance(data);
3404
- const intercepted = await ((_b = (_a = this.interceptors) === null || _a === void 0 ? void 0 : _a.request) === null || _b === void 0 ? void 0 : _b.call(_a, { instance }));
3405
- const builded = (intercepted === null || intercepted === void 0 ? void 0 : intercepted.instance) || instance;
3674
+ var FirestoreFieldType;
3675
+ (function (FirestoreFieldType) {
3676
+ FirestoreFieldType["String"] = "string";
3677
+ FirestoreFieldType["Number"] = "number";
3678
+ FirestoreFieldType["Boolean"] = "boolean";
3679
+ FirestoreFieldType["Timestamp"] = "timestamp";
3680
+ FirestoreFieldType["Array"] = "array";
3681
+ FirestoreFieldType["Map"] = "map";
3682
+ })(FirestoreFieldType || (FirestoreFieldType = {}));
3683
+
3684
+ const withFindFirestore = (MixinBase) => {
3685
+ const checkIfIsFilterOption = (filter) => !lodash.isNil(filter === null || filter === void 0 ? void 0 : filter.operator);
3686
+ const getValueFromFilter = (filter) => {
3687
+ return checkIfIsFilterOption(filter) ? filter.value : filter;
3688
+ };
3689
+ return class FindFirestore extends MixinBase {
3690
+ constructor() {
3691
+ super(...arguments);
3692
+ this.makeFirestoreWhere = (filter) => Object.keys(filter).reduce((queries, fieldName) => [
3693
+ ...queries,
3694
+ ...this.buildWhereSentence(fieldName, is(filter[fieldName])),
3695
+ ], []);
3696
+ this.buildWhereSentence = (fieldName, options) => {
3697
+ var _a, _b, _c, _d;
3698
+ if (this.isSubCollection(this) && fieldName === this.parentIdField)
3699
+ return [];
3700
+ const value = (options === null || options === void 0 ? void 0 : options.value) || options;
3701
+ const object = {};
3702
+ lodash.set(object, fieldName, value);
3703
+ const plainInstance = new this.model(object).toPlain();
3704
+ const firestoreFieldName = fieldName.toString().indexOf('.') > -1
3705
+ ? fieldName.toString()
3706
+ : Object.keys(plainInstance).find((key) => plainInstance[key]);
3707
+ if ((options === null || options === void 0 ? void 0 : options.operator) === exports.Where.LIKE) {
3708
+ if (Array.isArray(options === null || options === void 0 ? void 0 : options.value) &&
3709
+ (((_a = this.fields) === null || _a === void 0 ? void 0 : _a[firestoreFieldName]) ===
3710
+ FirestoreFieldType.Array ||
3711
+ !((_b = this.fields) === null || _b === void 0 ? void 0 : _b[firestoreFieldName])))
3712
+ return [[firestoreFieldName, 'array-contains-any', options.value]];
3713
+ return [
3714
+ [firestoreFieldName, '>=', options.value],
3715
+ [firestoreFieldName, '<=', `${options.value}~`],
3716
+ ];
3717
+ }
3718
+ if ((options === null || options === void 0 ? void 0 : options.operator) === exports.Where.IN &&
3719
+ Array.isArray(options === null || options === void 0 ? void 0 : options.value) &&
3720
+ (((_c = this.fields) === null || _c === void 0 ? void 0 : _c[firestoreFieldName]) ===
3721
+ FirestoreFieldType.Array ||
3722
+ !((_d = this.fields) === null || _d === void 0 ? void 0 : _d[firestoreFieldName])))
3723
+ return [[firestoreFieldName, 'array-contains', options.value]];
3724
+ if (lodash.isObject(options) && lodash.isNil(options === null || options === void 0 ? void 0 : options.operator) && lodash.isNil(options === null || options === void 0 ? void 0 : options.value)) {
3725
+ return Object.keys(options).reduce((queries, key) => [
3726
+ ...queries,
3727
+ ...this.buildWhereSentence(`${fieldName.toString()}.${key}`, is(options)[key]),
3728
+ ], []);
3729
+ }
3730
+ return [[firestoreFieldName, ((options === null || options === void 0 ? void 0 : options.operator) || '=='), (options === null || options === void 0 ? void 0 : options.value) || options]];
3731
+ };
3732
+ this.makeFirestoreOrderBy = (filters, fieldsToOrderBy) => {
3733
+ const orderByKeys = Object.keys(fieldsToOrderBy || {});
3734
+ if (!orderByKeys.length)
3735
+ return [];
3736
+ const filtersKeysWithUnordered = Object.keys(filters || {}).filter((filterKey) => !orderByKeys.includes(filterKey));
3737
+ if (filtersKeysWithUnordered.length)
3738
+ filtersKeysWithUnordered.forEach((filterKey) => (fieldsToOrderBy = Object.assign(Object.assign({}, (![exports.Where.EQUALS].includes(is(filters[filterKey]).operator)
3739
+ ? { [filterKey]: 'asc' }
3740
+ : {})), fieldsToOrderBy)));
3741
+ return Object.keys(fieldsToOrderBy).map((fieldName) => [
3742
+ fieldName,
3743
+ fieldsToOrderBy[fieldName],
3744
+ ]);
3745
+ };
3746
+ }
3747
+ generateCacheKey(findParams) {
3748
+ return FirestoreCacheKeyGeneratorHelper.generateFindCacheKey(this.model, findParams);
3749
+ }
3750
+ async find(find = {}, options) {
3751
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l;
3752
+ const logger = this.logger.with('find');
3753
+ if (((_a = this.cache) === null || _a === void 0 ? void 0 : _a.cacheAdapter) && ((_b = options === null || options === void 0 ? void 0 : options.cache) === null || _b === void 0 ? void 0 : _b.enabled) !== false) {
3754
+ const cacheKey = this.generateCacheKey(find);
3755
+ const cachedData = await this.cache.cacheAdapter.get(cacheKey);
3756
+ if (cachedData) {
3757
+ logger.log(`Dados recuperados do cache: ${cacheKey}`);
3758
+ return JSON.parse(cachedData);
3759
+ }
3760
+ }
3761
+ const collectionName = this.buildCollectionPathForFind(find.filters);
3762
+ const collection = this.collection(collectionName);
3763
+ const enableCount = (_d = (_c = find === null || find === void 0 ? void 0 : find.options) === null || _c === void 0 ? void 0 : _c.enableCount) !== null && _d !== void 0 ? _d : true;
3764
+ const req = { collection: collectionName, data: find };
3765
+ try {
3766
+ const intercepted = await ((_f = (_e = this.interceptors) === null || _e === void 0 ? void 0 : _e.request) === null || _f === void 0 ? void 0 : _f.call(_e, { find }));
3767
+ const { fields, filters, limits, orderBy } = (intercepted === null || intercepted === void 0 ? void 0 : intercepted.find) || find;
3768
+ const queries = this.makeFirestoreWhere(filters || {});
3769
+ const ordination = this.makeFirestoreOrderBy(filters, orderBy);
3770
+ const offsets = await this.defineLimits(filters, limits);
3771
+ const docs = await queries
3772
+ .reduce((collection, where) => collection.where(...where), ordination.reduce((collection, ordination) => collection.order(...ordination), offsets.reduce((collection, offset) => collection[offset[0]](offset[1]), collection)))
3773
+ .getDocs();
3774
+ const data = docs.docs.map((doc) => doc.data());
3775
+ const res = {
3776
+ data: (await ((_h = (_g = this.interceptors) === null || _g === void 0 ? void 0 : _g.response) === null || _h === void 0 ? void 0 : _h.call(_g, data, intercepted))) || data,
3777
+ count: enableCount ? this.calculateCount(data, limits) : Infinity,
3778
+ };
3779
+ logger.log({ req, queries, ordination, offsets, res });
3780
+ if (((_j = this.cache) === null || _j === void 0 ? void 0 : _j.cacheAdapter) && ((_k = options === null || options === void 0 ? void 0 : options.cache) === null || _k === void 0 ? void 0 : _k.enabled) !== false) {
3781
+ const cacheKey = this.generateCacheKey(find);
3782
+ await this.cache.cacheAdapter.set({
3783
+ key: cacheKey,
3784
+ data: JSON.stringify(res),
3785
+ expirationInSeconds: ((_l = options === null || options === void 0 ? void 0 : options.cache) === null || _l === void 0 ? void 0 : _l.ttl) || this.cache.ttlDefault,
3786
+ });
3787
+ logger.log(`Dados salvos no cache: ${cacheKey}`);
3788
+ }
3789
+ return res;
3790
+ }
3791
+ catch (error) {
3792
+ if (error instanceof Error)
3793
+ logger.log({ req, res: error, stack: error.stack });
3794
+ throw error;
3795
+ }
3796
+ }
3797
+ buildCollectionPathForFind(filters) {
3798
+ if (!this.isSubCollection(this))
3799
+ return this.collectionName;
3800
+ const parentIdField = this.parentIdField;
3801
+ const parentId = getValueFromFilter(filters === null || filters === void 0 ? void 0 : filters[parentIdField]);
3802
+ return `${this.parentRepository.collectionName}/${parentId}/${this.collectionName}`;
3803
+ }
3804
+ async defineLimits(filters, limits) {
3805
+ var _a;
3806
+ const queries = [];
3807
+ if (limits === null || limits === void 0 ? void 0 : limits.offset) {
3808
+ if (this.model.isModel(limits.offset))
3809
+ queries.push([
3810
+ 'fromStartAfter',
3811
+ await this.collection(this.buildCollectionPathForFind(filters))
3812
+ .getDoc((_a = Object.values(limits.offset.identifier).shift()) === null || _a === void 0 ? void 0 : _a.toString())
3813
+ .get(),
3814
+ ]);
3815
+ else if (lodash.isNumber(limits.offset) || lodash.isString(limits.offset)) {
3816
+ queries.push(['fromStartAt', limits.offset]);
3817
+ }
3818
+ }
3819
+ if (limits === null || limits === void 0 ? void 0 : limits.limit)
3820
+ queries.push(['limit', limits.limit]);
3821
+ return queries;
3822
+ }
3823
+ calculateCount(data, limits) {
3824
+ if (data.length <= 0)
3825
+ return 0;
3826
+ if (data.length < (limits === null || limits === void 0 ? void 0 : limits.limit))
3827
+ return data.length;
3828
+ return Infinity;
3829
+ }
3830
+ };
3831
+ };
3832
+
3833
+ const withCreateFirestore = (MixinBase) => {
3834
+ return class CreateFirestore extends MixinBase {
3835
+ async create(data) {
3836
+ var _a, _b, _c, _d;
3837
+ const logger = this.logger.with('create');
3838
+ const instance = this.model.toInstance(data);
3839
+ const intercepted = await ((_b = (_a = this.interceptors) === null || _a === void 0 ? void 0 : _a.request) === null || _b === void 0 ? void 0 : _b.call(_a, { instance }));
3840
+ const builded = (intercepted === null || intercepted === void 0 ? void 0 : intercepted.instance) || instance;
3406
3841
  const req = { collection: this.buildCollectionPathForAdd(builded), data };
3407
3842
  try {
3408
3843
  const docRef = await this.save(builded);
@@ -3454,24 +3889,41 @@ const withUpdateFirestore = (MixinBase) => {
3454
3889
  return options === null || options === void 0 ? void 0 : options.value;
3455
3890
  };
3456
3891
  return class UpdateFirestore extends MixinBase {
3892
+ getIdentifiersFromData(data) {
3893
+ const identifiers = {};
3894
+ const model = new this.model();
3895
+ const keyField = model.identifiersFields.shift();
3896
+ const identifierValue = getValueFromParams(data, keyField);
3897
+ identifiers[keyField] = identifierValue;
3898
+ return identifiers;
3899
+ }
3900
+ generateCacheKey(identifiers) {
3901
+ return FirestoreCacheKeyGeneratorHelper.generateGetCacheKey(this.model, identifiers);
3902
+ }
3457
3903
  async update(data) {
3458
- var _a, _b, _c, _d;
3904
+ var _a, _b, _c, _d, _e;
3459
3905
  const logger = this.logger.with('update');
3460
3906
  const collectionName = this.buildCollectionPathForUpdate(data);
3461
3907
  const model = new this.model();
3462
3908
  const keyField = model.identifiersFields.shift();
3463
3909
  const req = { collection: collectionName, data };
3910
+ if ((_a = this.cache) === null || _a === void 0 ? void 0 : _a.cacheAdapter) {
3911
+ const identifiers = this.getIdentifiersFromData(data);
3912
+ const cacheKey = this.generateCacheKey(identifiers);
3913
+ await this.cache.cacheAdapter.remove(cacheKey);
3914
+ logger.log(`Cache removido: ${cacheKey}`);
3915
+ }
3464
3916
  try {
3465
3917
  const identifiers = getValueFromParams(data, keyField);
3466
3918
  const docRef = this.collection(collectionName).getDoc(identifiers.toString());
3467
3919
  if (!(await docRef.get()).data())
3468
3920
  throw new NotFoundError(`Document '${collectionName}/${Object.values(identifiers.toString())}' not found`);
3469
3921
  const plainFromData = this.model.toInstance(this.paramsToPlain(data));
3470
- const intercepted = await ((_b = (_a = this.interceptors) === null || _a === void 0 ? void 0 : _a.request) === null || _b === void 0 ? void 0 : _b.call(_a, { instance: plainFromData }));
3922
+ const intercepted = await ((_c = (_b = this.interceptors) === null || _b === void 0 ? void 0 : _b.request) === null || _c === void 0 ? void 0 : _c.call(_b, { instance: plainFromData }));
3471
3923
  const builded = (intercepted === null || intercepted === void 0 ? void 0 : intercepted.instance) || plainFromData;
3472
3924
  await docRef.save(builded.toPlain());
3473
3925
  const docData = await docRef.get();
3474
- const res = ((_d = (_c = this.interceptors) === null || _c === void 0 ? void 0 : _c.response) === null || _d === void 0 ? void 0 : _d.call(_c, docData.data(), intercepted)) || docData.data();
3926
+ const res = ((_e = (_d = this.interceptors) === null || _d === void 0 ? void 0 : _d.response) === null || _e === void 0 ? void 0 : _e.call(_d, docData.data(), intercepted)) || docData.data();
3475
3927
  logger.log({ req, res, identifiers });
3476
3928
  return res;
3477
3929
  }
@@ -3497,17 +3949,25 @@ const withUpdateFirestore = (MixinBase) => {
3497
3949
 
3498
3950
  const withDeleteFirestore = (MixinBase) => {
3499
3951
  return class DeleteFirestore extends MixinBase {
3952
+ generateCacheKey(identifiers) {
3953
+ return FirestoreCacheKeyGeneratorHelper.generateGetCacheKey(this.model, identifiers);
3954
+ }
3500
3955
  async delete(identifiers) {
3501
- var _a, _b, _c, _d;
3956
+ var _a, _b, _c, _d, _e;
3502
3957
  const logger = this.logger.with('delete');
3503
3958
  const collectionName = this.buildCollectionPathForRemove(identifiers);
3504
3959
  const instance = this.model.toInstance(this.model.identifiersFields.reduce((acc, field) => (Object.assign(Object.assign({}, acc), { [field]: identifiers[field] })), {}));
3505
3960
  const req = { collection: collectionName, data: identifiers };
3961
+ if ((_a = this.cache) === null || _a === void 0 ? void 0 : _a.cacheAdapter) {
3962
+ const cacheKey = this.generateCacheKey(identifiers);
3963
+ await this.cache.cacheAdapter.remove(cacheKey);
3964
+ logger.log(`Cache removido: ${cacheKey}`);
3965
+ }
3506
3966
  try {
3507
- const intercepted = await ((_b = (_a = this.interceptors) === null || _a === void 0 ? void 0 : _a.request) === null || _b === void 0 ? void 0 : _b.call(_a, { instance }));
3967
+ const intercepted = await ((_c = (_b = this.interceptors) === null || _b === void 0 ? void 0 : _b.request) === null || _c === void 0 ? void 0 : _c.call(_b, { instance }));
3508
3968
  const builded = (intercepted === null || intercepted === void 0 ? void 0 : intercepted.instance) || instance;
3509
3969
  await this.collection(collectionName).getDoc(Object.values(builded.identifier).shift().toString()).delete();
3510
- await ((_d = (_c = this.interceptors) === null || _c === void 0 ? void 0 : _c.response) === null || _d === void 0 ? void 0 : _d.call(_c, instance, intercepted));
3970
+ await ((_e = (_d = this.interceptors) === null || _d === void 0 ? void 0 : _d.response) === null || _e === void 0 ? void 0 : _e.call(_d, instance, intercepted));
3511
3971
  logger.log({ req, res: undefined });
3512
3972
  }
3513
3973
  catch (error) {
@@ -3740,17 +4200,6 @@ class LogFirestoreRepository extends withCrudFirestore(withHelpers(withFirestore
3740
4200
  }
3741
4201
  }
3742
4202
 
3743
- class ProductQueueFirestoreRepository extends withCrudFirestore(withHelpers(withFirestore(Base))) {
3744
- constructor({ firestore, interceptors, }) {
3745
- super({
3746
- firestore,
3747
- collectionName: 'queue_products_functions',
3748
- model: ProductQueue,
3749
- interceptors,
3750
- });
3751
- }
3752
- }
3753
-
3754
4203
  class SequenceFirestoreRepository extends withCrudFirestore(withHelpers(withFirestore(Base))) {
3755
4204
  constructor({ firestore, interceptors }) {
3756
4205
  super({
@@ -3763,12 +4212,13 @@ class SequenceFirestoreRepository extends withCrudFirestore(withHelpers(withFire
3763
4212
  }
3764
4213
 
3765
4214
  class HomeFirestoreRepository extends withCrudFirestore(withHelpers(withFirestore(Base))) {
3766
- constructor({ firestore, interceptors }) {
4215
+ constructor({ firestore, interceptors, cache, }) {
3767
4216
  super({
3768
4217
  firestore,
3769
4218
  collectionName: 'dms',
3770
4219
  model: Home,
3771
4220
  interceptors,
4221
+ cache,
3772
4222
  });
3773
4223
  this.homeCategoryGroupToPlain = (homeCategoryGroup) => {
3774
4224
  var _a, _b, _c;
@@ -3825,89 +4275,97 @@ class HomeFirestoreRepository extends withCrudFirestore(withHelpers(withFirestor
3825
4275
  }
3826
4276
 
3827
4277
  class ShopMenuFirestoreRepository extends withCrudFirestore(withHelpers(withFirestore(Base))) {
3828
- constructor({ firestore, interceptors }) {
4278
+ constructor({ firestore, interceptors, cache, }) {
3829
4279
  super({
3830
4280
  firestore,
3831
4281
  collectionName: 'shopMenus',
3832
4282
  model: ShopMenu,
3833
4283
  interceptors,
4284
+ cache,
3834
4285
  });
3835
4286
  }
3836
4287
  }
3837
4288
 
3838
4289
  class ShopSettingsFirestoreRepository extends withCrudFirestore(withHelpers(withFirestore(Base))) {
3839
- constructor({ firestore, interceptors, }) {
4290
+ constructor({ firestore, interceptors, cache, }) {
3840
4291
  super({
3841
4292
  firestore,
3842
4293
  collectionName: 'shopSettings',
3843
4294
  model: ShopSettings,
3844
4295
  interceptors,
4296
+ cache,
3845
4297
  });
3846
4298
  }
3847
4299
  }
3848
4300
 
3849
4301
  class Buy2WinFirestoreRepository extends withCrudFirestore(withHelpers(withFirestore(Base))) {
3850
- constructor({ firestore, interceptors }) {
4302
+ constructor({ firestore, interceptors, cache, }) {
3851
4303
  super({
3852
4304
  firestore,
3853
4305
  collectionName: 'buy2win',
3854
4306
  model: Buy2Win,
3855
4307
  interceptors,
4308
+ cache,
3856
4309
  });
3857
4310
  }
3858
4311
  }
3859
4312
 
3860
4313
  class CampaignDashboardFirestoreRepository extends withCrudFirestore(withHelpers(withFirestore(Base))) {
3861
- constructor({ firestore, interceptors, }) {
4314
+ constructor({ firestore, interceptors, cache, }) {
3862
4315
  super({
3863
4316
  firestore,
3864
4317
  collectionName: 'dashboardCampaignsAuto',
3865
4318
  model: CampaignDashboard,
3866
4319
  interceptors,
4320
+ cache,
3867
4321
  });
3868
4322
  }
3869
4323
  }
3870
4324
 
3871
4325
  class CampaignHashtagFirestoreRepository extends withCrudFirestore(withHelpers(withFirestore(Base))) {
3872
- constructor({ firestore, interceptors, }) {
4326
+ constructor({ firestore, interceptors, cache, }) {
3873
4327
  super({
3874
4328
  firestore,
3875
4329
  collectionName: 'hashtagCampaignsAuto',
3876
4330
  model: CampaignHashtag,
3877
4331
  interceptors,
4332
+ cache,
3878
4333
  });
3879
4334
  }
3880
4335
  }
3881
4336
 
3882
4337
  class CheckoutFirestoreRepository extends withCrudFirestore(withHelpers(withFirestore(Base))) {
3883
- constructor({ firestore, interceptors }) {
4338
+ constructor({ firestore, interceptors, cache, }) {
3884
4339
  super({
3885
4340
  firestore,
3886
4341
  collectionName: 'checkouts',
3887
4342
  model: Checkout,
3888
4343
  interceptors,
4344
+ cache,
3889
4345
  });
3890
4346
  }
3891
4347
  }
3892
4348
 
3893
4349
  class CheckoutSubscriptionFirestoreRepository extends withCrudFirestore(withHelpers(withFirestore(Base))) {
3894
- constructor({ firestore, interceptors, }) {
4350
+ constructor({ firestore, interceptors, cache, }) {
3895
4351
  super({
3896
4352
  firestore,
3897
4353
  collectionName: 'checkoutsSubscription',
3898
4354
  model: CheckoutSubscription,
3899
4355
  interceptors,
4356
+ cache,
3900
4357
  });
3901
4358
  }
3902
4359
  }
3903
4360
 
3904
4361
  class CouponFirestoreRepository extends withCrudFirestore(withHelpers(withFirestore(Base))) {
3905
- constructor({ firestore, interceptors }) {
4362
+ constructor({ firestore, interceptors, cache, }) {
3906
4363
  super({
3907
4364
  firestore,
3908
4365
  collectionName: 'coupons',
3909
4366
  model: Coupon,
3910
4367
  interceptors,
4368
+ cache,
3911
4369
  });
3912
4370
  }
3913
4371
  buildModelInstance() {
@@ -3930,12 +4388,13 @@ class CouponFirestoreRepository extends withCrudFirestore(withHelpers(withFirest
3930
4388
  }
3931
4389
 
3932
4390
  class OrderFirestoreRepository extends withCrudFirestore(withHelpers(withFirestore(Base))) {
3933
- constructor({ firestore, interceptors }) {
4391
+ constructor({ firestore, interceptors, cache, }) {
3934
4392
  super({
3935
4393
  firestore,
3936
4394
  collectionName: 'orders',
3937
4395
  model: Order,
3938
4396
  interceptors,
4397
+ cache,
3939
4398
  fields: {
3940
4399
  status: FirestoreFieldType.String,
3941
4400
  },
@@ -3967,22 +4426,24 @@ class OrderFirestoreRepository extends withCrudFirestore(withHelpers(withFiresto
3967
4426
  }
3968
4427
 
3969
4428
  class LegacyOrderFirestoreRepository extends OrderFirestoreRepository {
3970
- constructor({ firestore, interceptors }) {
4429
+ constructor({ firestore, interceptors, cache, }) {
3971
4430
  super({
3972
4431
  firestore,
3973
4432
  interceptors,
4433
+ cache,
3974
4434
  });
3975
4435
  this.collectionName = 'legacyOrders';
3976
4436
  }
3977
4437
  }
3978
4438
 
3979
4439
  class OrderBlockedFirestoreRepository extends withCrudFirestore(withHelpers(withFirestore(Base))) {
3980
- constructor({ firestore, interceptors, }) {
4440
+ constructor({ firestore, interceptors, cache, }) {
3981
4441
  super({
3982
4442
  firestore,
3983
4443
  collectionName: 'paymentBlockedAttempts',
3984
4444
  model: OrderBlocked,
3985
4445
  interceptors,
4446
+ cache,
3986
4447
  });
3987
4448
  }
3988
4449
  async createBlockedOrderOrPayment(checkout, blockType, type, limiteRange, card = null) {
@@ -4014,130 +4475,141 @@ class OrderBlockedFirestoreRepository extends withCrudFirestore(withHelpers(with
4014
4475
  }
4015
4476
 
4016
4477
  class PaymentFirestoreRepository extends withCrudFirestore(withHelpers(withFirestore(Base))) {
4017
- constructor({ firestore, interceptors }) {
4478
+ constructor({ firestore, interceptors, cache, }) {
4018
4479
  super({
4019
4480
  firestore,
4020
4481
  collectionName: 'payments',
4021
4482
  model: Payment,
4022
4483
  interceptors,
4484
+ cache,
4023
4485
  });
4024
4486
  }
4025
4487
  }
4026
4488
 
4027
4489
  class SubscriptionPlanFirestoreRepository extends withCrudFirestore(withHelpers(withFirestore(Base))) {
4028
- constructor({ firestore, interceptors, }) {
4490
+ constructor({ firestore, interceptors, cache, }) {
4029
4491
  super({
4030
4492
  firestore,
4031
4493
  collectionName: 'subscriptionPlans',
4032
4494
  model: SubscriptionPlan,
4033
4495
  interceptors,
4496
+ cache,
4034
4497
  });
4035
4498
  }
4036
4499
  }
4037
4500
 
4038
4501
  class LeadFirestoreRepository extends withCrudFirestore(withHelpers(withFirestore(Base))) {
4039
- constructor({ firestore, interceptors }) {
4502
+ constructor({ firestore, interceptors, cache, }) {
4040
4503
  super({
4041
4504
  firestore,
4042
4505
  collectionName: 'leads',
4043
4506
  model: Lead,
4044
4507
  interceptors,
4508
+ cache,
4045
4509
  });
4046
4510
  }
4047
4511
  }
4048
4512
 
4049
4513
  class SubscriptionEditionFirestoreRepository extends withSubCollection(withCrudFirestore(withHelpers(withFirestore(Base)))) {
4050
- constructor({ firestore, interceptors }, parentRepository) {
4514
+ constructor({ firestore, interceptors, cache, }, parentRepository) {
4051
4515
  super({
4052
4516
  firestore,
4053
4517
  collectionName: 'editions',
4054
4518
  parentIdField: 'subscriptionId',
4055
4519
  model: Edition,
4056
4520
  interceptors,
4521
+ cache,
4057
4522
  });
4058
4523
  this.parentRepository = parentRepository;
4059
4524
  }
4060
4525
  }
4061
4526
 
4062
4527
  class SubscriptionFirestoreRepository extends withCrudFirestore(withHelpers(withFirestore(Base))) {
4063
- constructor({ firestore, interceptors, }) {
4528
+ constructor({ firestore, interceptors, cache, }) {
4064
4529
  super({
4065
4530
  firestore,
4066
4531
  collectionName: 'subscription',
4067
4532
  model: Subscription,
4068
4533
  interceptors,
4534
+ cache,
4069
4535
  });
4070
4536
  }
4071
4537
  }
4072
4538
 
4073
4539
  class SubscriptionMaterializationFirestoreRepository extends withCrudFirestore(withHelpers(withFirestore(Base))) {
4074
- constructor({ firestore, interceptors }) {
4540
+ constructor({ firestore, interceptors, cache, }) {
4075
4541
  super({
4076
4542
  firestore,
4077
4543
  collectionName: 'subscriptionMaterialization',
4078
4544
  model: SubscriptionMaterialization,
4079
4545
  interceptors,
4546
+ cache,
4080
4547
  });
4081
4548
  }
4082
4549
  }
4083
4550
 
4084
4551
  class SubscriptionPaymentFirestoreRepository extends withSubCollection(withCrudFirestore(withHelpers(withFirestore(Base)))) {
4085
- constructor({ firestore, interceptors }, parentRepository) {
4552
+ constructor({ firestore, interceptors, cache, }, parentRepository) {
4086
4553
  super({
4087
4554
  firestore,
4088
4555
  collectionName: 'payments',
4089
4556
  parentIdField: 'subscriptionId',
4090
4557
  model: SubscriptionPayment,
4091
4558
  interceptors,
4559
+ cache,
4092
4560
  });
4093
4561
  this.parentRepository = parentRepository;
4094
4562
  }
4095
4563
  }
4096
4564
 
4097
4565
  class SubscriptionSummaryFirestoreRepository extends withCrudFirestore(withHelpers(withFirestore(Base))) {
4098
- constructor({ firestore, interceptors, }) {
4566
+ constructor({ firestore, interceptors, cache, }) {
4099
4567
  super({
4100
4568
  firestore,
4101
4569
  collectionName: 'subscriptionSummary',
4102
4570
  model: SubscriptionSummary,
4103
4571
  interceptors,
4572
+ cache,
4104
4573
  });
4105
4574
  }
4106
4575
  }
4107
4576
 
4108
4577
  class UserAddressFirestoreRepository extends withSubCollection(withCrudFirestore(withHelpers(withFirestore(Base)))) {
4109
- constructor({ firestore, interceptors }, parentRepository) {
4578
+ constructor({ firestore, interceptors, cache, }, parentRepository) {
4110
4579
  super({
4111
4580
  firestore,
4112
4581
  collectionName: 'address',
4113
4582
  parentIdField: 'userId',
4114
4583
  model: UserAddress,
4115
4584
  interceptors,
4585
+ cache,
4116
4586
  });
4117
4587
  this.parentRepository = parentRepository;
4118
4588
  }
4119
4589
  }
4120
4590
 
4121
4591
  class UserBeautyProfileFirestoreRepository extends withSubCollection(withCrudFirestore(withHelpers(withFirestore(Base)))) {
4122
- constructor({ firestore, interceptors }, parentRepository) {
4592
+ constructor({ firestore, interceptors, cache, }, parentRepository) {
4123
4593
  super({
4124
4594
  firestore,
4125
4595
  collectionName: 'CX',
4126
4596
  parentIdField: 'userId',
4127
4597
  model: BeautyProfile,
4128
4598
  interceptors,
4599
+ cache,
4129
4600
  });
4130
4601
  this.parentRepository = parentRepository;
4131
4602
  }
4132
4603
  }
4133
4604
 
4134
4605
  class UserFirestoreRepository extends withCrudFirestore(withHelpers(withFirestore(Base))) {
4135
- constructor({ firestore, interceptors }) {
4606
+ constructor({ firestore, interceptors, cache, }) {
4136
4607
  super({
4137
4608
  firestore,
4138
4609
  collectionName: 'users',
4139
4610
  model: User,
4140
4611
  interceptors,
4612
+ cache,
4141
4613
  });
4142
4614
  }
4143
4615
  async get(identifiers) {
@@ -4197,13 +4669,14 @@ tslib.__decorate([
4197
4669
  ], UserFirestoreRepository.prototype, "checkIfExistsByField", null);
4198
4670
 
4199
4671
  class UserPaymentMethodFirestoreRepository extends withSubCollection(withCrudFirestore(withHelpers(withFirestore(Base)))) {
4200
- constructor({ firestore, interceptors }, parentRepository) {
4672
+ constructor({ firestore, interceptors, cache, }, parentRepository) {
4201
4673
  super({
4202
4674
  firestore,
4203
4675
  collectionName: 'payment_method',
4204
4676
  parentIdField: 'userId',
4205
4677
  model: UserPaymentMethod,
4206
4678
  interceptors,
4679
+ cache,
4207
4680
  });
4208
4681
  this.parentRepository = parentRepository;
4209
4682
  }
@@ -4255,391 +4728,112 @@ class ConnectDocumentService {
4255
4728
  }
4256
4729
  withConverter(params) {
4257
4730
  this.reference = this.reference.withConverter({
4258
- toFirestore: (data) => params.toFirestore(data),
4259
- fromFirestore: (snapshot, options) => params.fromFirestore(new ConnectBaseDocumentSnapshot(snapshot), options),
4260
- });
4261
- return this;
4262
- }
4263
- }
4264
-
4265
- class ConnectCollectionService {
4266
- constructor(path, firestore$1) {
4267
- this.firestore = firestore$1;
4268
- this.wheres = [];
4269
- this.orderBys = [];
4270
- this.reference = firestore.collection(firestore$1, path).withConverter({
4271
- toFirestore: (data) => data,
4272
- fromFirestore: (snapshot) => {
4273
- return Object.assign({ id: snapshot.id }, snapshot.data());
4274
- },
4275
- });
4276
- }
4277
- async add(data, id) {
4278
- const newDoc = await this.save(data, id);
4279
- return new ConnectDocumentService(newDoc.path, this.firestore).withConverter(this.converter);
4280
- }
4281
- async getDocs() {
4282
- if (this.startingAt > 0)
4283
- this.limitBy += this.startingAt;
4284
- const constraints = [
4285
- ...this.wheres,
4286
- ...this.orderBys,
4287
- ...(this.limitBy ? [firestore.limit(this.limitBy)] : []),
4288
- ];
4289
- return firestore.getDocs(firestore.query(this.reference, ...constraints)).then((docs) => {
4290
- const docsPaginated = this.startingAt > 0 ? docs.docs.slice(this.startingAt, this.limitBy) : docs.docs;
4291
- return {
4292
- empty: Boolean(docsPaginated.length),
4293
- size: docsPaginated.length,
4294
- docs: docsPaginated.map((doc) => new ConnectBaseDocumentSnapshot(doc)),
4295
- };
4296
- });
4297
- }
4298
- getDoc(id) {
4299
- return new ConnectDocumentService(`${this.reference.path}/${id}`, this.firestore).withConverter(this.converter);
4300
- }
4301
- where(attribute, operator, value) {
4302
- this.wheres.push(firestore.where(attribute, operator, value));
4303
- return this;
4304
- }
4305
- order(attribute, order) {
4306
- this.orderBys.push(firestore.orderBy(attribute, order));
4307
- return this;
4308
- }
4309
- limit(quantity) {
4310
- this.limitBy = quantity;
4311
- return this;
4312
- }
4313
- offset(offsetBy) {
4314
- this.offsetBy = offsetBy;
4315
- return this;
4316
- }
4317
- fromStartAt(startingAt) {
4318
- this.startingAt = startingAt;
4319
- return this;
4320
- }
4321
- fromStartAfter(startingAt) {
4322
- this.startingAfter = firestore.startAfter(startingAt);
4323
- return this;
4324
- }
4325
- withConverter(params) {
4326
- this.converter = params;
4327
- this.reference = this.reference.withConverter({
4328
- toFirestore: (data) => params.toFirestore(data),
4329
- fromFirestore: (snapshot, options) => params.fromFirestore(new ConnectBaseDocumentSnapshot(snapshot), options),
4330
- });
4331
- return this;
4332
- }
4333
- async save(data, id) {
4334
- if (lodash.isEmpty(id))
4335
- return firestore.addDoc(this.reference, data);
4336
- const docRef = firestore.doc(this.reference, id);
4337
- await firestore.setDoc(docRef, data);
4338
- return docRef;
4339
- }
4340
- }
4341
-
4342
- class ConnectFirestoreService {
4343
- constructor(firestore) {
4344
- this.firestore = firestore;
4345
- }
4346
- getCollection(path) {
4347
- return new ConnectCollectionService(path, this.firestore);
4348
- }
4349
- getDocument(path) {
4350
- return new ConnectDocumentService(path, this.firestore);
4351
- }
4352
- }
4353
-
4354
- class FirebaseFileUploaderService {
4355
- constructor(storage, baseUrl) {
4356
- this.storage = storage;
4357
- this.baseUrl = baseUrl;
4358
- }
4359
- async upload(path, file) {
4360
- const storageRef = storage.ref(this.storage, path);
4361
- return storage.uploadBytes(storageRef, file).then((reference) => `${this.baseUrl}/${reference.ref.bucket}/${reference.ref.fullPath}`);
4362
- }
4363
- }
4364
-
4365
- class AttributeOptionHelper {
4366
- }
4367
- AttributeOptionHelper.FindByAttribute = (attributeName, fields) => {
4368
- var _a;
4369
- if (fields.includes(attributeName))
4370
- return { columnName: attributeName.toString(), attributeName, to: (value) => value, from: (value) => value };
4371
- const field = fields.find((columnOption) => lodash.isObject(columnOption) && Object.keys(columnOption).includes(attributeName.toString()));
4372
- const fieldOption = (_a = is(field)) === null || _a === void 0 ? void 0 : _a[attributeName];
4373
- if (lodash.isNil(fieldOption))
4374
- return { columnName: attributeName.toString(), attributeName };
4375
- if (Array.isArray(fieldOption))
4376
- return { columnName: attributeName.toString(), attributeName, fields: fieldOption };
4377
- return Object.assign({ attributeName, columnName: attributeName.toString() }, fieldOption);
4378
- };
4379
- AttributeOptionHelper.CheckIsColumnOption = (fieldValue) => !!(fieldValue === null || fieldValue === void 0 ? void 0 : fieldValue.columnName);
4380
- AttributeOptionHelper.FindColumnOptionFromList = (columnName, fields) => {
4381
- if (fields.includes(columnName))
4382
- return { columnName, attributeName: columnName };
4383
- const field = is(fields.find((field) => {
4384
- if (!lodash.isObject(field))
4385
- return false;
4386
- const columnOption = Object.values(field).find((option) => AttributeOptionHelper.CheckIsColumnOption(option) && option.columnName === columnName ? option : {});
4387
- return AttributeOptionHelper.CheckIsColumnOption(columnOption) && (columnOption === null || columnOption === void 0 ? void 0 : columnOption.columnName) === columnName;
4388
- }) || {});
4389
- const attributeName = Object.keys(field).find((fieldOptionFromList) => AttributeOptionHelper.CheckIsColumnOption(field[fieldOptionFromList]) || Array.isArray(field[fieldOptionFromList]));
4390
- const fieldOption = field === null || field === void 0 ? void 0 : field[attributeName];
4391
- if (Array.isArray(fieldOption))
4392
- return { attributeName: attributeName, fields: fieldOption };
4393
- return Object.assign({ attributeName: attributeName || columnName, columnName }, fieldOption);
4394
- };
4395
-
4396
- var HasuraGraphQLWhere;
4397
- (function (HasuraGraphQLWhere) {
4398
- HasuraGraphQLWhere["EQUALS"] = "_eq";
4399
- HasuraGraphQLWhere["GT"] = "_gt";
4400
- HasuraGraphQLWhere["GTE"] = "_gte";
4401
- HasuraGraphQLWhere["IN"] = "_in";
4402
- HasuraGraphQLWhere["NOTIN"] = "_nin";
4403
- HasuraGraphQLWhere["LT"] = "_lt";
4404
- HasuraGraphQLWhere["LTE"] = "_lte";
4405
- HasuraGraphQLWhere["LIKE"] = "_like";
4406
- HasuraGraphQLWhere["ILIKE"] = "_ilike";
4407
- HasuraGraphQLWhere["NOTLIKE"] = "_nlike";
4408
- HasuraGraphQLWhere["ISNULL"] = "_is_null";
4409
- HasuraGraphQLWhere["ISNOTNULL"] = "_is_null";
4410
- HasuraGraphQLWhere["JSON_CONTAINS"] = "_contains";
4411
- HasuraGraphQLWhere["JSON_HAS_KEYS_ANY"] = "_has_keys_any";
4412
- HasuraGraphQLWhere["IREGEX"] = "_iregex";
4413
- HasuraGraphQLWhere["REGEX"] = "_regex";
4414
- })(HasuraGraphQLWhere || (HasuraGraphQLWhere = {}));
4415
-
4416
- var HasuraGraphQLColumnType;
4417
- (function (HasuraGraphQLColumnType) {
4418
- HasuraGraphQLColumnType["Int"] = "Int";
4419
- HasuraGraphQLColumnType["Float"] = "Float";
4420
- HasuraGraphQLColumnType["Boolean"] = "Boolean";
4421
- HasuraGraphQLColumnType["String"] = "String";
4422
- HasuraGraphQLColumnType["DateTime"] = "timestampz";
4423
- HasuraGraphQLColumnType["Json"] = "json";
4424
- HasuraGraphQLColumnType["Jsonb"] = "jsonb";
4425
- HasuraGraphQLColumnType["Enum"] = "enum";
4426
- HasuraGraphQLColumnType["Uuid"] = "uuid";
4427
- })(HasuraGraphQLColumnType || (HasuraGraphQLColumnType = {}));
4428
-
4429
- class FilterOptionHelper {
4430
- }
4431
- FilterOptionHelper.CheckIfIsFilterOption = (filter) => !lodash.isNil(filter === null || filter === void 0 ? void 0 : filter.operator);
4432
- FilterOptionHelper.GetValueFromFilter = (filter, fieldOption) => {
4433
- if (!FilterOptionHelper.CheckIfIsFilterOption(filter))
4434
- return filter;
4435
- if (filter.operator === exports.Where.ISNULL)
4436
- return true;
4437
- if (filter.operator === exports.Where.ISNOTNULL)
4438
- return false;
4439
- const converter = fieldOption.to
4440
- ? fieldOption.to
4441
- : (value) => filter.operator === exports.Where.LIKE && !Array.isArray(filter.value) && value.indexOf('%') < 0
4442
- ? `%${value}%`
4443
- : value;
4444
- const converterResult = Array.isArray(filter.value) && !fieldOption.fields && [exports.Where.IN, exports.Where.NOTIN].includes(filter.operator)
4445
- ? filter.value.map((fieldValue) => converter(fieldValue))
4446
- : converter(filter.value);
4447
- const newValue = filter.ignoreCase && !filter.ignoreAccent && !Array.isArray(filter.value) && converterResult.indexOf('%') < 0
4448
- ? `%${converterResult}%`
4449
- : converterResult;
4450
- return filter.ignoreAccent && !Array.isArray(filter.value)
4451
- ? FilterOptionHelper.buildInsensitiveSentence(newValue)
4452
- : newValue;
4453
- };
4454
- FilterOptionHelper.buildInsensitiveSentence = (value) => {
4455
- const valueWithoutAccents = FilterOptionHelper.removeAccents(value);
4456
- let result = '';
4457
- for (const char of valueWithoutAccents) {
4458
- const allCharOptions = [];
4459
- if (['a', 'e', 'i', 'o', 'u', 'c', 'A', 'E', 'I', 'O', 'U', 'C'].includes(char)) {
4460
- const charOptions = {
4461
- a: ['á', 'â', 'ã', 'à', 'a'],
4462
- e: ['é', 'ê', 'ẽ', 'è', 'e'],
4463
- i: ['í', 'î', 'ĩ', 'ì', 'i'],
4464
- o: ['ó', 'ô', 'õ', 'ò', 'o'],
4465
- u: ['ú', 'û', 'ũ', 'ù', 'u'],
4466
- c: ['ç', 'c'],
4467
- A: ['Á', 'Â', 'Ã', 'À', 'A'],
4468
- E: ['É', 'Ê', 'Ẽ', 'È', 'E'],
4469
- I: ['Í', 'Î', 'Ĩ', 'Ì', 'I'],
4470
- O: ['Ó', 'Ô', 'Õ', 'Ò', 'O'],
4471
- U: ['Ú', 'Û', 'Ũ', 'Ù', 'U'],
4472
- C: ['Ç', 'C'],
4473
- };
4474
- allCharOptions.push(...charOptions[char]);
4475
- result += `[${allCharOptions.join('')}]`;
4476
- }
4477
- else {
4478
- result += char;
4479
- }
4480
- }
4481
- return result;
4482
- };
4483
- FilterOptionHelper.removeAccents = (text) => {
4484
- return text.normalize('NFD').replace(/[\u0300-\u036f]/g, '');
4485
- };
4486
-
4487
- class BindFilterQueryHelper {
4488
- }
4489
- BindFilterQueryHelper.MakeGraphQLWhere = (filter, fields) => Object.keys(filter).reduce((variables, fieldName) => {
4490
- const columnOption = AttributeOptionHelper.FindByAttribute(fieldName, fields);
4491
- if (!columnOption.bindFindFilter)
4492
- return Object.assign(Object.assign({}, variables), {
4493
- [columnOption.columnName]: BindFilterQueryHelper.BuildWhereSentence(fieldName, filter[fieldName], fields),
4494
- });
4495
- const builtFilter = columnOption.bindFindFilter(filter[fieldName]);
4496
- return Object.assign(Object.assign({}, variables), Object.keys(builtFilter).reduce((variablesList, columnName) => (Object.assign(Object.assign({}, variablesList), { [columnName]: BindFilterQueryHelper.BuildWhereSentence(fieldName, builtFilter[columnName], fields) })), {}));
4497
- }, {});
4498
- BindFilterQueryHelper.BuildWhereSentence = (field, options, fields) => {
4499
- const fieldSentenceOptions = AttributeOptionHelper.FindByAttribute(field, fields);
4500
- const isNestedField = !Array.isArray(options) &&
4501
- lodash.isObject(options) &&
4502
- lodash.isNil(options === null || options === void 0 ? void 0 : options.operator) &&
4503
- lodash.isNil(options === null || options === void 0 ? void 0 : options.value) &&
4504
- lodash.isNil(fieldSentenceOptions === null || fieldSentenceOptions === void 0 ? void 0 : fieldSentenceOptions.to);
4505
- if (isNestedField)
4506
- return Object.keys(options).reduce((variables, key) => {
4507
- const fieldOptions = AttributeOptionHelper.FindByAttribute(key, (fieldSentenceOptions === null || fieldSentenceOptions === void 0 ? void 0 : fieldSentenceOptions.fields) || fields);
4508
- const columnName = fieldOptions.columnName;
4509
- const columnFields = fieldOptions.fields;
4510
- return Object.assign(Object.assign({}, variables), { [columnName]: BindFilterQueryHelper.BuildWhereSentence(key, is(is(options)[key]), (fieldSentenceOptions === null || fieldSentenceOptions === void 0 ? void 0 : fieldSentenceOptions.fields) || columnFields || fields) });
4511
- }, {});
4512
- if (!Array.isArray(options) && !lodash.isNil(fieldSentenceOptions.fields))
4513
- return {
4514
- [fieldSentenceOptions.fields[0]]: BindFilterQueryHelper.BuildOperatorSentence(options, fieldSentenceOptions),
4515
- };
4516
- if (!Array.isArray(options) && lodash.isObject(options) && !FilterOptionHelper.CheckIfIsFilterOption(options))
4517
- options = Object.values(options)[0];
4518
- return Array.isArray(options)
4519
- ? options.reduce((whereSentence, option) => (Object.assign(Object.assign({}, whereSentence), BindFilterQueryHelper.BuildOperatorSentence(option, fieldSentenceOptions))), {})
4520
- : BindFilterQueryHelper.BuildOperatorSentence(options, fieldSentenceOptions);
4521
- };
4522
- BindFilterQueryHelper.BuildOperatorSentence = (options, fieldOption) => ({
4523
- [BindFilterQueryHelper.GetHasuraOperator(options, fieldOption)]: FilterOptionHelper.GetValueFromFilter(options, fieldOption),
4524
- });
4525
- BindFilterQueryHelper.GetHasuraOperator = (options, fieldOption) => FilterOptionHelper.CheckIfIsFilterOption(options)
4526
- ? fieldOption.type === HasuraGraphQLColumnType.Jsonb
4527
- ? BindFilterQueryHelper.GetHasuraJsonbOperator(options)
4528
- : options.operator === exports.Where.LIKE && options.ignoreCase && options.ignoreAccent
4529
- ? HasuraGraphQLWhere.IREGEX
4530
- : options.operator === exports.Where.LIKE && options.ignoreAccent
4531
- ? HasuraGraphQLWhere.REGEX
4532
- : options.operator === exports.Where.LIKE && options.ignoreCase
4533
- ? HasuraGraphQLWhere.ILIKE
4534
- : HasuraGraphQLWhere[Object.keys(HasuraGraphQLWhere).find((graphQLOperator) => graphQLOperator ===
4535
- Object.keys(exports.Where).find((operator) => exports.Where[operator] === (options === null || options === void 0 ? void 0 : options.operator)))]
4536
- : HasuraGraphQLWhere.EQUALS;
4537
- BindFilterQueryHelper.GetHasuraJsonbOperator = (options) => options.operator === exports.Where.IN
4538
- ? HasuraGraphQLWhere.JSON_CONTAINS
4539
- : options.operator === exports.Where.LIKE
4540
- ? HasuraGraphQLWhere.JSON_HAS_KEYS_ANY
4541
- : HasuraGraphQLWhere[Object.keys(HasuraGraphQLWhere).find((graphQLOperator) => graphQLOperator ===
4542
- Object.keys(exports.Where).find((operator) => exports.Where[operator] === (options === null || options === void 0 ? void 0 : options.operator)))];
4543
-
4544
- class GraphQLFieldHelper {
4545
- }
4546
- GraphQLFieldHelper.CheckIsGraphQLParams = (params) => !lodash.isString(params) && Array.isArray(params) && params.length >= 0 && !!params[0].operation;
4547
- GraphQLFieldHelper.ConvertModelFieldsToGraphQLFields = (fields) => {
4548
- return fields === null || fields === void 0 ? void 0 : fields.map((field) => {
4549
- if (lodash.isString(field))
4550
- return field.toString();
4551
- if (field === 'affected_rows')
4552
- return field;
4553
- const fieldName = Object.keys(field).shift();
4554
- const fieldValue = is(field[fieldName]);
4555
- if (Array.isArray(fieldValue))
4556
- return { [fieldName]: GraphQLFieldHelper.ConvertModelFieldsToGraphQLFields(fieldValue) };
4557
- if (!AttributeOptionHelper.CheckIsColumnOption(fieldValue))
4558
- return;
4559
- const isNestedField = !!fieldValue.fields;
4560
- if (isNestedField)
4561
- return GraphQLFieldHelper.ConvertNestedFieldsToGraphQLFields(fieldName, fieldValue);
4562
- return fieldValue.columnName;
4563
- }).filter((field) => !!field);
4564
- };
4565
- GraphQLFieldHelper.ConvertFieldValueFrom = (data, fields) => Object.keys(data).reduce((result, columnName) => {
4566
- const { attributeName, fields: attributeFields, from, } = AttributeOptionHelper.FindColumnOptionFromList(columnName, fields);
4567
- if (!!attributeFields && Array.isArray(attributeFields)) {
4568
- if (Array.isArray(data[columnName]))
4569
- return Object.assign(Object.assign({}, result), { [attributeName]: from
4570
- ? from(data[columnName], data)
4571
- : is(data[columnName]).map((value) => GraphQLFieldHelper.ConvertFieldValueFrom(is(value), attributeFields)) });
4572
- if (lodash.isObject(data[columnName]))
4573
- return Object.assign(Object.assign({}, result), { [attributeName]: !!from
4574
- ? from(data[columnName])
4575
- : GraphQLFieldHelper.ConvertFieldValueFrom(is(data[columnName]), attributeFields) });
4731
+ toFirestore: (data) => params.toFirestore(data),
4732
+ fromFirestore: (snapshot, options) => params.fromFirestore(new ConnectBaseDocumentSnapshot(snapshot), options),
4733
+ });
4734
+ return this;
4576
4735
  }
4577
- if (!!from)
4578
- return Object.assign(Object.assign({}, result), { [attributeName]: from(data[columnName], data) });
4579
- return Object.assign(Object.assign({}, result), { [attributeName]: lodash.isString(data[columnName]) ? parseDateTime(data[columnName].toString()) : data[columnName] });
4580
- }, {});
4581
- GraphQLFieldHelper.ConvertFieldValueTo = (instance, fields, update = false) => {
4582
- var _a;
4583
- const data = ((_a = instance.toPlain) === null || _a === void 0 ? void 0 : _a.call(instance)) || instance;
4584
- return Object.keys(data).reduce((result, attributeName) => {
4585
- const { columnName, fields: attributeFields, foreignKeyColumn, to, bindPersistData, } = AttributeOptionHelper.FindByAttribute(attributeName, fields);
4586
- if (bindPersistData)
4587
- return Object.assign(Object.assign({}, result), bindPersistData(data[attributeName], instance));
4588
- if (lodash.isNil(columnName))
4589
- return result;
4590
- if (!!foreignKeyColumn &&
4591
- !lodash.isEmpty(foreignKeyColumn) &&
4592
- !Object.keys(foreignKeyColumn).filter((key) => { var _a; return !((_a = is(data[attributeName])) === null || _a === void 0 ? void 0 : _a[key]); }).length)
4593
- return Object.keys(foreignKeyColumn).reduce((object, current) => {
4594
- var _a;
4595
- const { columnName: foreignColumnName } = AttributeOptionHelper.FindByAttribute(foreignKeyColumn[current], fields);
4596
- return Object.assign(Object.assign({}, object), { [foreignColumnName]: (_a = data[attributeName]) === null || _a === void 0 ? void 0 : _a[current] });
4597
- }, Object.assign({}, result));
4598
- if (update &&
4599
- lodash.isObject(data[attributeName]) &&
4600
- !lodash.isNil(attributeFields) &&
4601
- !lodash.isDate(data[attributeName]))
4602
- return result;
4603
- if (!!columnName &&
4604
- Array.isArray(attributeFields) &&
4605
- lodash.isObject(data[attributeName])) {
4606
- const converted = !lodash.isNil(columnName) && to
4607
- ? to(instance[attributeName], instance)
4608
- : data[attributeName];
4609
- return Object.assign(Object.assign({}, result), (converted !== undefined
4610
- ? {
4611
- [columnName]: {
4612
- data: instance[attributeName] instanceof BaseModel
4613
- ? GraphQLFieldHelper.ConvertFieldValueTo(data[attributeName], attributeFields)
4614
- : converted,
4615
- },
4616
- }
4617
- : {}));
4618
- }
4619
- if (!!to)
4620
- return Object.assign(Object.assign({}, result), { [columnName]: to(instance[attributeName], instance) });
4621
- return Object.assign(Object.assign({}, result), { [columnName]: data[attributeName] });
4622
- }, {});
4623
- };
4624
- GraphQLFieldHelper.ConvertNestedFieldsToGraphQLFields = (fieldName, fieldValue) => {
4625
- const hasCustomFilters = !!fieldValue.filters;
4626
- if (hasCustomFilters)
4627
- return {
4628
- operation: fieldValue.columnName || fieldName,
4629
- fields: GraphQLFieldHelper.ConvertModelFieldsToGraphQLFields(fieldValue.fields),
4630
- variables: {
4631
- [`${fieldValue.columnName}_where`]: {
4632
- name: 'where',
4633
- type: fieldValue.filters.filterType,
4634
- value: BindFilterQueryHelper.MakeGraphQLWhere(fieldValue.filters.filters, fieldValue.fields),
4635
- required: true,
4636
- },
4736
+ }
4737
+
4738
+ class ConnectCollectionService {
4739
+ constructor(path, firestore$1) {
4740
+ this.firestore = firestore$1;
4741
+ this.wheres = [];
4742
+ this.orderBys = [];
4743
+ this.reference = firestore.collection(firestore$1, path).withConverter({
4744
+ toFirestore: (data) => data,
4745
+ fromFirestore: (snapshot) => {
4746
+ return Object.assign({ id: snapshot.id }, snapshot.data());
4637
4747
  },
4638
- };
4639
- return {
4640
- [fieldValue.columnName || fieldName]: GraphQLFieldHelper.ConvertModelFieldsToGraphQLFields(fieldValue.fields),
4641
- };
4642
- };
4748
+ });
4749
+ }
4750
+ async add(data, id) {
4751
+ const newDoc = await this.save(data, id);
4752
+ return new ConnectDocumentService(newDoc.path, this.firestore).withConverter(this.converter);
4753
+ }
4754
+ async getDocs() {
4755
+ if (this.startingAt > 0)
4756
+ this.limitBy += this.startingAt;
4757
+ const constraints = [
4758
+ ...this.wheres,
4759
+ ...this.orderBys,
4760
+ ...(this.limitBy ? [firestore.limit(this.limitBy)] : []),
4761
+ ];
4762
+ return firestore.getDocs(firestore.query(this.reference, ...constraints)).then((docs) => {
4763
+ const docsPaginated = this.startingAt > 0 ? docs.docs.slice(this.startingAt, this.limitBy) : docs.docs;
4764
+ return {
4765
+ empty: Boolean(docsPaginated.length),
4766
+ size: docsPaginated.length,
4767
+ docs: docsPaginated.map((doc) => new ConnectBaseDocumentSnapshot(doc)),
4768
+ };
4769
+ });
4770
+ }
4771
+ getDoc(id) {
4772
+ return new ConnectDocumentService(`${this.reference.path}/${id}`, this.firestore).withConverter(this.converter);
4773
+ }
4774
+ where(attribute, operator, value) {
4775
+ this.wheres.push(firestore.where(attribute, operator, value));
4776
+ return this;
4777
+ }
4778
+ order(attribute, order) {
4779
+ this.orderBys.push(firestore.orderBy(attribute, order));
4780
+ return this;
4781
+ }
4782
+ limit(quantity) {
4783
+ this.limitBy = quantity;
4784
+ return this;
4785
+ }
4786
+ offset(offsetBy) {
4787
+ this.offsetBy = offsetBy;
4788
+ return this;
4789
+ }
4790
+ fromStartAt(startingAt) {
4791
+ this.startingAt = startingAt;
4792
+ return this;
4793
+ }
4794
+ fromStartAfter(startingAt) {
4795
+ this.startingAfter = firestore.startAfter(startingAt);
4796
+ return this;
4797
+ }
4798
+ withConverter(params) {
4799
+ this.converter = params;
4800
+ this.reference = this.reference.withConverter({
4801
+ toFirestore: (data) => params.toFirestore(data),
4802
+ fromFirestore: (snapshot, options) => params.fromFirestore(new ConnectBaseDocumentSnapshot(snapshot), options),
4803
+ });
4804
+ return this;
4805
+ }
4806
+ async save(data, id) {
4807
+ if (lodash.isEmpty(id))
4808
+ return firestore.addDoc(this.reference, data);
4809
+ const docRef = firestore.doc(this.reference, id);
4810
+ await firestore.setDoc(docRef, data);
4811
+ return docRef;
4812
+ }
4813
+ }
4814
+
4815
+ class ConnectFirestoreService {
4816
+ constructor(firestore) {
4817
+ this.firestore = firestore;
4818
+ }
4819
+ getCollection(path) {
4820
+ return new ConnectCollectionService(path, this.firestore);
4821
+ }
4822
+ getDocument(path) {
4823
+ return new ConnectDocumentService(path, this.firestore);
4824
+ }
4825
+ }
4826
+
4827
+ class FirebaseFileUploaderService {
4828
+ constructor(storage, baseUrl) {
4829
+ this.storage = storage;
4830
+ this.baseUrl = baseUrl;
4831
+ }
4832
+ async upload(path, file) {
4833
+ const storageRef = storage.ref(this.storage, path);
4834
+ return storage.uploadBytes(storageRef, file).then((reference) => `${this.baseUrl}/${reference.ref.bucket}/${reference.ref.fullPath}`);
4835
+ }
4836
+ }
4643
4837
 
4644
4838
  const withCreateHasuraGraphQL = (MixinBase) => {
4645
4839
  return class CreateHasuraGraphQLMixin extends MixinBase {
@@ -4688,7 +4882,13 @@ const withDeleteHasuraGraphQL = (MixinBase) => {
4688
4882
  this.deleteGraphQLOperation = (options === null || options === void 0 ? void 0 : options.deleteGraphQLOperation) || `delete_${this.tableName}_by_pk`;
4689
4883
  }
4690
4884
  async delete(identifiers) {
4885
+ var _a;
4691
4886
  this.logger = DebugHelper.from(this, 'delete');
4887
+ if ((_a = this.cache) === null || _a === void 0 ? void 0 : _a.cacheAdapter) {
4888
+ const cacheKey = CacheKeyGeneratorHelper.generateCacheKeyFromIdentifiers(this.model, identifiers);
4889
+ await this.cache.cacheAdapter.remove(cacheKey);
4890
+ this.logger.log(`Cache removido: ${cacheKey}`);
4891
+ }
4692
4892
  const instance = this.model.toInstance(identifiers);
4693
4893
  await this.mutation(this.deleteGraphQLOperation, this.model.identifiersFields.map((field) => AttributeOptionHelper.FindByAttribute(field, this.fields).columnName), this.model.identifiersFields.reduce((ids, identifier) => {
4694
4894
  const identifierBinded = identifier;
@@ -4726,6 +4926,7 @@ const withHasuraGraphQL = (MixinBase) => {
4726
4926
  this.model = options.model;
4727
4927
  this.fields = options.fields || this.model.identifiersFields;
4728
4928
  this.logger = DebugHelper.from(this);
4929
+ this.cache = options.cache;
4729
4930
  }
4730
4931
  async mutation(operation, fields, variables) {
4731
4932
  const resultQuery = gqlQueryBuilder.mutation({
@@ -4827,9 +5028,29 @@ const withUpdateHasuraGraphQL = (MixinBase) => {
4827
5028
  this.updateGraphQLObjectType = (options === null || options === void 0 ? void 0 : options.updateGraphQLObjectType) || `${this.tableName}_set_input`;
4828
5029
  this.updateGraphQLPKType = (options === null || options === void 0 ? void 0 : options.updateGraphQLPKType) || `${this.tableName}_pk_columns_input`;
4829
5030
  }
5031
+ getIdentifiersFromData(data) {
5032
+ const instance = this.model.toInstance(data);
5033
+ const identifiers = {};
5034
+ this.model.identifiersFields.forEach((identifier) => {
5035
+ const field = identifier;
5036
+ if (!lodash.isNil(instance[field])) {
5037
+ identifiers[String(field)] = instance[field];
5038
+ }
5039
+ });
5040
+ return identifiers;
5041
+ }
4830
5042
  async update(data) {
5043
+ var _a;
4831
5044
  this.logger = DebugHelper.from(this, 'update');
4832
5045
  const plainData = this.paramsToPlain(data);
5046
+ if ((_a = this.cache) === null || _a === void 0 ? void 0 : _a.cacheAdapter) {
5047
+ const identifiers = this.getIdentifiersFromData(plainData);
5048
+ if (Object.keys(identifiers).length > 0) {
5049
+ const cacheKey = CacheKeyGeneratorHelper.generateCacheKeyFromIdentifiers(this.model, identifiers);
5050
+ await this.cache.cacheAdapter.remove(cacheKey);
5051
+ this.logger.log(`Cache removido: ${cacheKey}`);
5052
+ }
5053
+ }
4833
5054
  await this.mutation(this.updateGraphQLOperation, this.model.identifiersFields.map((field) => AttributeOptionHelper.FindByAttribute(field, this.fields).columnName), {
4834
5055
  _set: {
4835
5056
  type: this.updateGraphQLObjectType,
@@ -4870,8 +5091,20 @@ const withGetHasuraGraphQL = (MixinBase) => {
4870
5091
  super(...params);
4871
5092
  this.getGraphQLOperation = (options === null || options === void 0 ? void 0 : options.getGraphQLOperation) || `${this.tableName}_by_pk`;
4872
5093
  }
4873
- async get(identifiers) {
5094
+ generateCacheKey(identifiers) {
5095
+ return CacheKeyGeneratorHelper.generateCacheKeyFromIdentifiers(this.model, identifiers);
5096
+ }
5097
+ async get(identifiers, options) {
5098
+ var _a, _b, _c, _d, _e;
4874
5099
  this.logger = DebugHelper.from(this, 'get');
5100
+ if (((_a = this.cache) === null || _a === void 0 ? void 0 : _a.cacheAdapter) && ((_b = options === null || options === void 0 ? void 0 : options.cache) === null || _b === void 0 ? void 0 : _b.enabled)) {
5101
+ const cacheKey = this.generateCacheKey(identifiers);
5102
+ const cachedData = await this.cache.cacheAdapter.get(cacheKey);
5103
+ if (cachedData) {
5104
+ this.logger.log(`Dados recuperados do cache: ${cacheKey}`);
5105
+ return this.model.toInstance(JSON.parse(cachedData));
5106
+ }
5107
+ }
4875
5108
  const instance = this.model.toInstance(identifiers);
4876
5109
  const result = await this.query(this.getGraphQLOperation, this.fields, this.model.identifiersFields.reduce((ids, identifier) => {
4877
5110
  var _a;
@@ -4890,12 +5123,26 @@ const withGetHasuraGraphQL = (MixinBase) => {
4890
5123
  const data = result[this.getGraphQLOperation];
4891
5124
  if (lodash.isNil(data))
4892
5125
  throw new NotFoundError(`${instance.constructor.name} not found`);
4893
- return this.convertDataFromHasura(result[this.getGraphQLOperation]);
5126
+ const resultModel = this.convertDataFromHasura(result[this.getGraphQLOperation]);
5127
+ if (((_c = this.cache) === null || _c === void 0 ? void 0 : _c.cacheAdapter) && ((_d = options === null || options === void 0 ? void 0 : options.cache) === null || _d === void 0 ? void 0 : _d.enabled)) {
5128
+ const cacheKey = this.generateCacheKey(identifiers);
5129
+ await this.cache.cacheAdapter.set({
5130
+ key: cacheKey,
5131
+ data: JSON.stringify(resultModel.toPlain()),
5132
+ expirationInSeconds: ((_e = options === null || options === void 0 ? void 0 : options.cache) === null || _e === void 0 ? void 0 : _e.ttl) || this.cache.ttlDefault,
5133
+ });
5134
+ this.logger.log(`Dados salvos no cache: ${cacheKey}`);
5135
+ }
5136
+ return resultModel;
4894
5137
  }
4895
5138
  };
4896
5139
  };
4897
5140
 
4898
5141
  const withFindHasuraGraphQL = (MixinBase) => {
5142
+ const generateCacheKey = (model, params) => {
5143
+ const md5 = MD5GeneratorHelper.generateMD5(params);
5144
+ return `${model.name.toLowerCase()}:find:${md5}`;
5145
+ };
4899
5146
  return class FindHasuraGraphQLMixin extends MixinBase {
4900
5147
  constructor() {
4901
5148
  super(...arguments);
@@ -4934,12 +5181,20 @@ const withFindHasuraGraphQL = (MixinBase) => {
4934
5181
  return ((_a = AttributeOptionHelper.FindByAttribute(attr.toString().split('.').pop(), fields)) === null || _a === void 0 ? void 0 : _a.columnName) || attr;
4935
5182
  });
4936
5183
  }
4937
- async find(params) {
4938
- var _a, _b, _c, _d, _e, _f, _g;
5184
+ async find(params, options) {
5185
+ var _a, _b, _c, _d, _e, _f, _g, _h;
4939
5186
  this.logger = DebugHelper.from(this, 'find');
4940
- const { filters, limits, orderBy, options } = params || {};
5187
+ const { filters, limits, orderBy, options: findOptions } = params || {};
4941
5188
  const tableFiltersNamed = `${this.tableName}:${JSON.stringify(filters)}`;
4942
- const enableCount = (_a = options === null || options === void 0 ? void 0 : options.enableCount) !== null && _a !== void 0 ? _a : true;
5189
+ const enableCount = (_a = findOptions === null || findOptions === void 0 ? void 0 : findOptions.enableCount) !== null && _a !== void 0 ? _a : true;
5190
+ if (((_b = this.cache) === null || _b === void 0 ? void 0 : _b.cacheAdapter) && ((_c = options === null || options === void 0 ? void 0 : options.cache) === null || _c === void 0 ? void 0 : _c.enabled)) {
5191
+ const cacheKey = generateCacheKey(this.model, params);
5192
+ const cachedData = await this.cache.cacheAdapter.get(cacheKey);
5193
+ if (cachedData) {
5194
+ this.logger.log(`Dados recuperados do cache: ${cacheKey}`);
5195
+ return this.bindResult(JSON.parse(cachedData), { enableCount, findOptions, tableFiltersNamed });
5196
+ }
5197
+ }
4943
5198
  const variablesFilters = lodash.isNil(filters)
4944
5199
  ? {}
4945
5200
  : {
@@ -4990,7 +5245,7 @@ const withFindHasuraGraphQL = (MixinBase) => {
4990
5245
  ]
4991
5246
  : []),
4992
5247
  ...((!this.lastDistinct[tableFiltersNamed] &&
4993
- ((_c = (_b = params.options) === null || _b === void 0 ? void 0 : _b.distinct) === null || _c === void 0 ? void 0 : _c.map((distinct) => {
5248
+ ((_e = (_d = params.options) === null || _d === void 0 ? void 0 : _d.distinct) === null || _e === void 0 ? void 0 : _e.map((distinct) => {
4994
5249
  var _a, _b;
4995
5250
  const distinctOption = (_a = this.fields.find((fieldOption) => fieldOption === distinct)) !== null && _a !== void 0 ? _a : this.fields.find((fieldOption) => Object.keys(fieldOption).shift() === distinct);
4996
5251
  const fieldName = ((_b = Object.values(distinctOption).shift()) === null || _b === void 0 ? void 0 : _b.columnName) || distinct;
@@ -5010,29 +5265,43 @@ const withFindHasuraGraphQL = (MixinBase) => {
5010
5265
  }))) ||
5011
5266
  []),
5012
5267
  ]);
5268
+ if (((_f = this.cache) === null || _f === void 0 ? void 0 : _f.cacheAdapter) && ((_g = options === null || options === void 0 ? void 0 : options.cache) === null || _g === void 0 ? void 0 : _g.enabled)) {
5269
+ const cacheKey = generateCacheKey(this.model, params);
5270
+ await this.cache.cacheAdapter.set({
5271
+ key: cacheKey,
5272
+ data: JSON.stringify(result),
5273
+ expirationInSeconds: ((_h = options === null || options === void 0 ? void 0 : options.cache) === null || _h === void 0 ? void 0 : _h.ttl) || this.cache.ttlDefault,
5274
+ });
5275
+ this.logger.log(`Dados salvos no cache: ${cacheKey}`);
5276
+ }
5277
+ return this.bindResult(result, { enableCount, findOptions, tableFiltersNamed });
5278
+ }
5279
+ bindResult(result, { enableCount, findOptions, tableFiltersNamed, }) {
5280
+ var _a, _b, _c, _d;
5013
5281
  const data = result[this.tableName].map((row) => this.convertDataFromHasura(row));
5014
- return Object.assign(Object.assign(Object.assign({ data, count: enableCount ? result[`${this.tableName}_aggregate`].aggregate.count : Infinity }, (((_d = options === null || options === void 0 ? void 0 : options.minimal) === null || _d === void 0 ? void 0 : _d.length)
5282
+ const findResult = Object.assign(Object.assign(Object.assign({ data, count: enableCount ? result[`${this.tableName}_aggregate`].aggregate.count : Infinity }, (((_a = findOptions === null || findOptions === void 0 ? void 0 : findOptions.minimal) === null || _a === void 0 ? void 0 : _a.length)
5015
5283
  ? {
5016
- minimal: options.minimal.reduce((minimals, current) => {
5284
+ minimal: findOptions.minimal.reduce((minimals, current) => {
5017
5285
  var _a;
5018
5286
  return (Object.assign(Object.assign({}, minimals), lodash.set(minimals, current, result[`${this.tableName}_aggregate`].aggregate.min[((_a = AttributeOptionHelper.FindByAttribute(current.toString().split('.').pop(), this.fields)) === null || _a === void 0 ? void 0 : _a.columnName) || current])));
5019
5287
  }, {}),
5020
5288
  }
5021
- : {})), (((_e = options === null || options === void 0 ? void 0 : options.maximum) === null || _e === void 0 ? void 0 : _e.length)
5289
+ : {})), (((_b = findOptions === null || findOptions === void 0 ? void 0 : findOptions.maximum) === null || _b === void 0 ? void 0 : _b.length)
5022
5290
  ? {
5023
- maximum: options.maximum.reduce((maximums, current) => {
5291
+ maximum: findOptions.maximum.reduce((maximums, current) => {
5024
5292
  var _a;
5025
5293
  return (Object.assign(Object.assign({}, maximums), lodash.set(maximums, current, result[`${this.tableName}_aggregate`].aggregate.max[((_a = AttributeOptionHelper.FindByAttribute(current.toString().split('.').pop(), this.fields)) === null || _a === void 0 ? void 0 : _a.columnName) || current])));
5026
5294
  }, {}),
5027
5295
  }
5028
- : {})), (((_f = options === null || options === void 0 ? void 0 : options.distinct) === null || _f === void 0 ? void 0 : _f.length) && {
5029
- distinct: (_g = this.lastDistinct[tableFiltersNamed]) !== null && _g !== void 0 ? _g : (this.lastDistinct[tableFiltersNamed] = options === null || options === void 0 ? void 0 : options.distinct.reduce((distinct, current) => {
5296
+ : {})), (((_c = findOptions === null || findOptions === void 0 ? void 0 : findOptions.distinct) === null || _c === void 0 ? void 0 : _c.length) && {
5297
+ distinct: (_d = this.lastDistinct[tableFiltersNamed]) !== null && _d !== void 0 ? _d : (this.lastDistinct[tableFiltersNamed] = findOptions === null || findOptions === void 0 ? void 0 : findOptions.distinct.reduce((distinct, current) => {
5030
5298
  var _a, _b;
5031
5299
  const distinctOption = (_a = this.fields.find((fieldOption) => fieldOption === current)) !== null && _a !== void 0 ? _a : this.fields.find((fieldOption) => Object.keys(fieldOption).shift() === current);
5032
5300
  const fieldName = ((_b = Object.values(distinctOption).shift()) === null || _b === void 0 ? void 0 : _b.columnName) || current;
5033
5301
  return Object.assign(Object.assign({}, distinct), { [current.toString()]: result[`${this.tableName}_${current.toString()}_distinct`].map((obj) => obj[fieldName]) });
5034
5302
  }, {})),
5035
5303
  }));
5304
+ return findResult;
5036
5305
  }
5037
5306
  };
5038
5307
  };
@@ -5074,7 +5343,7 @@ tslib.__decorate([
5074
5343
  ], ProductErrorsHasuraGraphQL.prototype, "product", void 0);
5075
5344
 
5076
5345
  class CategoryCollectionChildrenHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGraphQL(Base)) {
5077
- constructor({ endpoint, authOptions, interceptors, }) {
5346
+ constructor({ endpoint, authOptions, interceptors, cache, }) {
5078
5347
  super({
5079
5348
  tableName: 'category_collection_children',
5080
5349
  model: CategoryCollectionChildren,
@@ -5105,12 +5374,13 @@ class CategoryCollectionChildrenHasuraGraphQLRepository extends withCrudHasuraGr
5105
5374
  },
5106
5375
  },
5107
5376
  ],
5377
+ cache,
5108
5378
  });
5109
5379
  }
5110
5380
  }
5111
5381
 
5112
5382
  class CategoryFilterHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGraphQL(Base)) {
5113
- constructor({ endpoint, authOptions, interceptors, }) {
5383
+ constructor({ endpoint, authOptions, interceptors, cache, }) {
5114
5384
  super({
5115
5385
  tableName: 'category_filter',
5116
5386
  model: CategoryFilter,
@@ -5192,6 +5462,7 @@ class CategoryFilterHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHa
5192
5462
  },
5193
5463
  },
5194
5464
  ],
5465
+ cache,
5195
5466
  });
5196
5467
  }
5197
5468
  deleteByCategory(categoryId) {
@@ -5227,13 +5498,14 @@ tslib.__decorate([
5227
5498
  ], CategoryFilterHasuraGraphQLRepository.prototype, "deleteByCategoryAndFilter", null);
5228
5499
 
5229
5500
  class CategoryHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGraphQL(Base)) {
5230
- constructor({ endpoint, authOptions, interceptors, }, productRepository, categoryFilterRepository) {
5501
+ constructor({ endpoint, authOptions, interceptors, cache, }, productRepository, categoryFilterRepository) {
5231
5502
  super({
5232
5503
  tableName: 'category',
5233
5504
  model: Category,
5234
5505
  endpoint,
5235
5506
  authOptions,
5236
5507
  interceptors,
5508
+ cache,
5237
5509
  fields: [
5238
5510
  { id: { columnName: 'id', to: (value) => +value, from: (value) => value.toString() } },
5239
5511
  { firestoreId: { columnName: 'firestore_id' } },
@@ -5349,11 +5621,12 @@ class CategoryHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGr
5349
5621
  },
5350
5622
  } }));
5351
5623
  }
5352
- async get(identifiers) {
5624
+ async get(identifiers, optionsCache) {
5353
5625
  var _a;
5354
5626
  return Number.isNaN(+identifiers.id)
5355
- ? (_a = (await this.find({ filters: { firestoreId: identifiers.id }, options: { enableCount: false } })).data) === null || _a === void 0 ? void 0 : _a[0]
5356
- : super.get(identifiers);
5627
+ ? (_a = (await this.find({ filters: { firestoreId: identifiers.id }, options: { enableCount: false } }, optionsCache))
5628
+ .data) === null || _a === void 0 ? void 0 : _a[0]
5629
+ : super.get(identifiers, optionsCache);
5357
5630
  }
5358
5631
  async update(params) {
5359
5632
  const { products, id: checkId, metadatas, filters } = params, data = tslib.__rest(params, ["products", "id", "metadatas", "filters"]);
@@ -5365,7 +5638,7 @@ class CategoryHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGr
5365
5638
  category.filters = filters && (await this.updateFilters(+id, { filters }));
5366
5639
  return category;
5367
5640
  }
5368
- async getCategoryBySlug(slug, shop) {
5641
+ async getCategoryBySlug(slug, shop, optionsCache) {
5369
5642
  if (!slug)
5370
5643
  return null;
5371
5644
  const { data } = await this.find({
@@ -5377,14 +5650,14 @@ class CategoryHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGr
5377
5650
  options: {
5378
5651
  enableCount: false,
5379
5652
  },
5380
- });
5653
+ }, optionsCache);
5381
5654
  if (!data.length)
5382
5655
  throw new NotFoundError(`Category with slug ${slug} not found`);
5383
5656
  if (data.length > 1)
5384
5657
  throw new DuplicatedResultsError('Query returned duplicated values');
5385
5658
  return data.shift();
5386
5659
  }
5387
- async getCategoryByShop(shop) {
5660
+ async getCategoryByShop(shop, optionsCache) {
5388
5661
  if (!shop)
5389
5662
  return;
5390
5663
  const { data } = await this.find({
@@ -5396,10 +5669,10 @@ class CategoryHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGr
5396
5669
  options: {
5397
5670
  enableCount: false,
5398
5671
  },
5399
- });
5672
+ }, optionsCache);
5400
5673
  return data;
5401
5674
  }
5402
- async getCategoriesForHome(categoryIds, shop, limit = 4) {
5675
+ async getCategoriesForHome(categoryIds, shop, limit = 4, optionsCache) {
5403
5676
  if (!(categoryIds === null || categoryIds === void 0 ? void 0 : categoryIds.length))
5404
5677
  return [];
5405
5678
  const categoriesFirestore = categoryIds.filter((categoryId) => Number.isNaN(+categoryId));
@@ -5407,36 +5680,37 @@ class CategoryHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGr
5407
5680
  const categories = [];
5408
5681
  if (categoriesFirestore.length)
5409
5682
  categories.push(...(await this.find({
5410
- filters: { firestoreId: { operator: exports.Where.IN, value: categoriesFirestore.filter(Boolean) }, published: true },
5411
- }).then(({ data }) => data)));
5683
+ filters: {
5684
+ firestoreId: { operator: exports.Where.IN, value: categoriesFirestore.filter(Boolean) },
5685
+ published: true,
5686
+ },
5687
+ }, optionsCache).then(({ data }) => data)));
5412
5688
  if (categoriesHasura.length)
5413
5689
  categories.push(...(await this.find({
5414
5690
  filters: {
5415
5691
  id: { operator: exports.Where.IN, value: categoriesHasura.filter(Boolean) },
5416
5692
  published: true,
5417
5693
  },
5418
- }).then(({ data }) => data)));
5694
+ }, optionsCache).then(({ data }) => data)));
5419
5695
  if (!categories.length)
5420
5696
  return [];
5421
5697
  const homeSections = await Promise.all(categories.map(async (category) => ({
5422
5698
  category,
5423
- products: await this.mountCategory(category, shop, { limit, hasStock: true }),
5699
+ products: await this.mountCategory(category, shop, { limit, hasStock: true }, optionsCache),
5424
5700
  })));
5425
5701
  return homeSections;
5426
5702
  }
5427
- async mountCategory(category, shop, options) {
5703
+ async mountCategory(category, shop, options, optionsCache) {
5428
5704
  var _a;
5429
5705
  if (!((_a = category === null || category === void 0 ? void 0 : category.products) === null || _a === void 0 ? void 0 : _a.length))
5430
5706
  return [];
5431
5707
  const mostRelevants = category.getMostRelevantByShop(shop);
5432
5708
  const mostRelevantProductsIds = [...new Set(mostRelevants.concat(category.products))];
5433
5709
  const products = [];
5434
- const { data: productsData } = await this.productRepository.findCatalog({
5435
- filters: {
5436
- id: { operator: exports.Where.IN, value: mostRelevantProductsIds },
5437
- published: true,
5438
- },
5439
- fields: [
5710
+ const { data: productsData } = await this.productRepository.findCatalog(Object.assign(Object.assign({ filters: Object.assign({ id: {
5711
+ operator: exports.Where.IN,
5712
+ value: mostRelevantProductsIds,
5713
+ }, published: true }, (options.hasStock ? { stock: { quantity: { operator: exports.Where.GT, value: 0 } } } : {})) }, (options.limit ? { limits: { limit: options.limit } } : {})), { fields: [
5440
5714
  'id',
5441
5715
  'name',
5442
5716
  'slug',
@@ -5462,15 +5736,12 @@ class CategoryHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGr
5462
5736
  'shoppingCount',
5463
5737
  'gender',
5464
5738
  'createdAt',
5465
- ],
5466
- options: { enableCount: false },
5467
- orderBy: {
5739
+ ], options: { enableCount: false }, orderBy: {
5740
+ stock: 'desc',
5468
5741
  shoppingCount: 'desc',
5469
5742
  rate: 'desc',
5470
- stock: 'desc',
5471
5743
  name: 'asc',
5472
- },
5473
- }, shop === exports.Shops.MENSMARKET ? 'male' : 'female');
5744
+ } }), shop === exports.Shops.MENSMARKET ? 'male' : 'female', optionsCache);
5474
5745
  const mostRelevantWithouyStock = productsData.filter((product) => mostRelevants.includes(product.id) && product.stock.quantity <= 0);
5475
5746
  const firstProducts = productsData
5476
5747
  .filter((product) => mostRelevants.includes(product.id) && product.stock.quantity > 0)
@@ -5483,7 +5754,7 @@ class CategoryHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGr
5483
5754
  products.push(...resultFinal);
5484
5755
  return products;
5485
5756
  }
5486
- async getChildren(parentId) {
5757
+ async getChildren(parentId, _optionsCache) {
5487
5758
  const { category_tree } = await this.query('category_tree', ['id', 'name', 'parent_id', 'slug', 'reference', 'published', 'shops'], {
5488
5759
  args: {
5489
5760
  type: 'category_tree_args',
@@ -5621,31 +5892,31 @@ class CategoryHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGr
5621
5892
  tslib.__decorate([
5622
5893
  Log(),
5623
5894
  tslib.__metadata("design:type", Function),
5624
- tslib.__metadata("design:paramtypes", [String, String]),
5895
+ tslib.__metadata("design:paramtypes", [String, String, Object]),
5625
5896
  tslib.__metadata("design:returntype", Promise)
5626
5897
  ], CategoryHasuraGraphQLRepository.prototype, "getCategoryBySlug", null);
5627
5898
  tslib.__decorate([
5628
5899
  Log(),
5629
5900
  tslib.__metadata("design:type", Function),
5630
- tslib.__metadata("design:paramtypes", [String]),
5901
+ tslib.__metadata("design:paramtypes", [String, Object]),
5631
5902
  tslib.__metadata("design:returntype", Promise)
5632
5903
  ], CategoryHasuraGraphQLRepository.prototype, "getCategoryByShop", null);
5633
5904
  tslib.__decorate([
5634
5905
  Log(),
5635
5906
  tslib.__metadata("design:type", Function),
5636
- tslib.__metadata("design:paramtypes", [Array, String, Object]),
5907
+ tslib.__metadata("design:paramtypes", [Array, String, Object, Object]),
5637
5908
  tslib.__metadata("design:returntype", Promise)
5638
5909
  ], CategoryHasuraGraphQLRepository.prototype, "getCategoriesForHome", null);
5639
5910
  tslib.__decorate([
5640
5911
  Log(),
5641
5912
  tslib.__metadata("design:type", Function),
5642
- tslib.__metadata("design:paramtypes", [Category, String, Object]),
5913
+ tslib.__metadata("design:paramtypes", [Category, String, Object, Object]),
5643
5914
  tslib.__metadata("design:returntype", Promise)
5644
5915
  ], CategoryHasuraGraphQLRepository.prototype, "mountCategory", null);
5645
5916
  tslib.__decorate([
5646
5917
  Log(),
5647
5918
  tslib.__metadata("design:type", Function),
5648
- tslib.__metadata("design:paramtypes", [Number]),
5919
+ tslib.__metadata("design:paramtypes", [Number, Object]),
5649
5920
  tslib.__metadata("design:returntype", Promise)
5650
5921
  ], CategoryHasuraGraphQLRepository.prototype, "getChildren", null);
5651
5922
  tslib.__decorate([
@@ -5656,7 +5927,7 @@ tslib.__decorate([
5656
5927
  ], CategoryHasuraGraphQLRepository.prototype, "isChild", null);
5657
5928
 
5658
5929
  class CategoryProductHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGraphQL(Base)) {
5659
- constructor({ endpoint, authOptions, interceptors, }) {
5930
+ constructor({ endpoint, authOptions, interceptors, cache, }) {
5660
5931
  super({
5661
5932
  tableName: 'category_product',
5662
5933
  model: CategoryProduct,
@@ -5664,6 +5935,7 @@ class CategoryProductHasuraGraphQLRepository extends withCrudHasuraGraphQL(withH
5664
5935
  authOptions,
5665
5936
  interceptors,
5666
5937
  fields: [{ productId: { columnName: 'product_id' } }, { categoryId: { columnName: 'category_id' } }, 'order'],
5938
+ cache,
5667
5939
  });
5668
5940
  }
5669
5941
  async removeProductFromCategory(categoryId, productId) {
@@ -5690,7 +5962,7 @@ class CategoryProductHasuraGraphQLRepository extends withCrudHasuraGraphQL(withH
5690
5962
  }
5691
5963
 
5692
5964
  class FilterHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGraphQL(Base)) {
5693
- constructor({ endpoint, authOptions, interceptors, }, filterOptionRepository, categoryFilterRepository) {
5965
+ constructor({ endpoint, authOptions, interceptors, cache, }, filterOptionRepository, categoryFilterRepository) {
5694
5966
  super({
5695
5967
  tableName: 'filter',
5696
5968
  model: Filter,
@@ -5730,6 +6002,7 @@ class FilterHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGrap
5730
6002
  },
5731
6003
  },
5732
6004
  ],
6005
+ cache,
5733
6006
  });
5734
6007
  this.filterOptionRepository = filterOptionRepository;
5735
6008
  this.categoryFilterRepository = categoryFilterRepository;
@@ -5816,7 +6089,7 @@ tslib.__decorate([
5816
6089
  ], FilterHasuraGraphQLRepository.prototype, "deleteOptions", null);
5817
6090
 
5818
6091
  class FilterOptionHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGraphQL(Base)) {
5819
- constructor({ endpoint, authOptions, interceptors, }) {
6092
+ constructor({ endpoint, authOptions, interceptors, cache, }) {
5820
6093
  super({
5821
6094
  tableName: 'filter_option',
5822
6095
  model: FilterOption,
@@ -5830,18 +6103,20 @@ class FilterOptionHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasu
5830
6103
  { createdAt: { columnName: 'created_at' } },
5831
6104
  { updatedAt: { columnName: 'updated_at' } },
5832
6105
  ],
6106
+ cache,
5833
6107
  });
5834
6108
  }
5835
6109
  }
5836
6110
 
5837
6111
  class ProductErrorsHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGraphQL(Base)) {
5838
- constructor({ endpoint, authOptions, interceptors, }, productRepository) {
6112
+ constructor({ endpoint, authOptions, interceptors, cache, }, productRepository) {
5839
6113
  super({
5840
6114
  tableName: 'product_errors',
5841
6115
  model: ProductErrorsHasuraGraphQL,
5842
6116
  endpoint,
5843
6117
  authOptions,
5844
6118
  interceptors,
6119
+ cache,
5845
6120
  fields: [
5846
6121
  {
5847
6122
  productId: {
@@ -5928,7 +6203,7 @@ class ProductHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGra
5928
6203
  { updatedAt: { columnName: 'updated_at' } },
5929
6204
  ];
5930
6205
  }
5931
- constructor({ endpoint, authOptions, interceptors, }) {
6206
+ constructor({ endpoint, authOptions, interceptors, cache, }) {
5932
6207
  super({
5933
6208
  tableName: 'product',
5934
6209
  model: ProductHasuraGraphQL,
@@ -5936,6 +6211,7 @@ class ProductHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGra
5936
6211
  authOptions,
5937
6212
  interceptors,
5938
6213
  fields: [],
6214
+ cache,
5939
6215
  });
5940
6216
  this.bindReviewToModel = (plain) => ProductReview.toInstance(Object.assign(Object.assign({}, is(lodash.omit(plain, ['product_id', 'created_at', 'updated_at', 'person_id', 'order_id']))), { createdAt: typeof plain.created_at === 'string' ? new Date(plain.created_at) : plain.created_at, updatedAt: typeof plain.updated_at === 'string' ? new Date(plain.updated_at) : plain.updated_at, personId: plain.person_id, orderId: plain.order_id }));
5941
6217
  this.bindReviewToHasura = (review) => (Object.assign(Object.assign({}, is(lodash.omit(review, ['productId', 'createdAt', 'updatedAt', 'personId', 'orderId']))), { person_id: review.personId, order_id: review.orderId }));
@@ -6120,17 +6396,18 @@ class ProductHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGra
6120
6396
  }
6121
6397
  return product;
6122
6398
  }
6123
- async get(identifiers) {
6399
+ async get(identifiers, options) {
6124
6400
  var _a;
6125
6401
  const product = Number.isNaN(+identifiers.id)
6126
- ? (_a = (await this.find({ filters: { firestoreId: identifiers.id }, options: { enableCount: false } })).data) === null || _a === void 0 ? void 0 : _a[0]
6127
- : await super.get(identifiers);
6402
+ ? (_a = (await this.find({ filters: { firestoreId: identifiers.id }, options: { enableCount: false } }, options))
6403
+ .data) === null || _a === void 0 ? void 0 : _a[0]
6404
+ : await super.get(identifiers, options);
6128
6405
  if (product.productId)
6129
6406
  throw new NotFoundError('Product not found, it is a variant');
6130
- product.reviews = product.reviews || (await this.findReviewsByProduct(+product.id));
6407
+ product.reviews = product.reviews || (await this.findReviewsByProduct(+product.id, options));
6131
6408
  return product;
6132
6409
  }
6133
- async find(params) {
6410
+ async find(params, optionsParams) {
6134
6411
  var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m;
6135
6412
  const _o = params || {}, { filters, fields } = _o, options = tslib.__rest(_o, ["filters", "fields"]);
6136
6413
  const bindFields = fields ||
@@ -6152,10 +6429,18 @@ class ProductHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGra
6152
6429
  'fullPrice',
6153
6430
  ]
6154
6431
  : []),
6155
- ] }));
6432
+ ] }), optionsParams);
6156
6433
  }
6157
- async getBySlug(slug) {
6158
- var _a;
6434
+ async getBySlug(slug, options) {
6435
+ var _a, _b, _c, _d, _e, _f;
6436
+ if (((_a = this.cache) === null || _a === void 0 ? void 0 : _a.cacheAdapter) && ((_b = options === null || options === void 0 ? void 0 : options.cache) === null || _b === void 0 ? void 0 : _b.enabled)) {
6437
+ const cacheKey = `${this.model.name.toLowerCase()}:slug:${slug}`;
6438
+ const cachedData = await this.cache.cacheAdapter.get(cacheKey);
6439
+ if (cachedData) {
6440
+ this.logger.log(`Dados recuperados do cache: ${cacheKey}`);
6441
+ return this.model.toInstance(JSON.parse(cachedData));
6442
+ }
6443
+ }
6159
6444
  const result = await this.find({
6160
6445
  filters: {
6161
6446
  slug,
@@ -6167,8 +6452,17 @@ class ProductHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGra
6167
6452
  });
6168
6453
  if (!result.data.length)
6169
6454
  return null;
6170
- const product = (_a = result === null || result === void 0 ? void 0 : result.data) === null || _a === void 0 ? void 0 : _a.shift();
6455
+ const product = (_c = result === null || result === void 0 ? void 0 : result.data) === null || _c === void 0 ? void 0 : _c.shift();
6171
6456
  RoundProductPricesHelper.roundProductPrices(product);
6457
+ if (((_d = this.cache) === null || _d === void 0 ? void 0 : _d.cacheAdapter) && ((_e = options === null || options === void 0 ? void 0 : options.cache) === null || _e === void 0 ? void 0 : _e.enabled) && product) {
6458
+ const cacheKey = `${this.model.name.toLowerCase()}:slug:${slug}`;
6459
+ await this.cache.cacheAdapter.set({
6460
+ key: cacheKey,
6461
+ data: JSON.stringify(product.toPlain()),
6462
+ expirationInSeconds: ((_f = options === null || options === void 0 ? void 0 : options.cache) === null || _f === void 0 ? void 0 : _f.ttl) || this.cache.ttlDefault,
6463
+ });
6464
+ this.logger.log(`Dados salvos no cache: ${cacheKey}`);
6465
+ }
6172
6466
  return product;
6173
6467
  }
6174
6468
  async update(params) {
@@ -6181,13 +6475,22 @@ class ProductHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGra
6181
6475
  product.metadata = metadata && (await this.updateMetadata(+id, { metadata }));
6182
6476
  return product;
6183
6477
  }
6184
- async fetchProductReviews() {
6478
+ async fetchProductReviews(filters, options) {
6479
+ var _a, _b, _c, _d, _e;
6480
+ if (((_a = this.cache) === null || _a === void 0 ? void 0 : _a.cacheAdapter) && ((_b = options === null || options === void 0 ? void 0 : options.cache) === null || _b === void 0 ? void 0 : _b.enabled)) {
6481
+ const cacheKey = `${this.model.name.toLowerCase()}:all-reviews:${MD5GeneratorHelper.generateMD5(filters)}`;
6482
+ const cachedData = await this.cache.cacheAdapter.get(cacheKey);
6483
+ if (cachedData) {
6484
+ this.logger.log(`Dados recuperados do cache: ${cacheKey}`);
6485
+ return JSON.parse(cachedData);
6486
+ }
6487
+ }
6185
6488
  let data = [];
6186
6489
  let count = 0;
6187
6490
  let offset = 0;
6188
- const limit = 500;
6491
+ const limit = (filters === null || filters === void 0 ? void 0 : filters.limit) || 500;
6189
6492
  do {
6190
- const result = await super.find(Object.assign({ fields: ['id', 'name', 'sku', 'reviews'] }, ({
6493
+ const result = await super.find(Object.assign({ fields: ['id', 'name', 'sku', 'reviews'] }, (limit && {
6191
6494
  limits: {
6192
6495
  offset,
6193
6496
  limit,
@@ -6197,12 +6500,50 @@ class ProductHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGra
6197
6500
  count = result.data.length;
6198
6501
  offset += limit;
6199
6502
  } while (count === limit);
6200
- return data.reduce((reviews, product) => [
6503
+ const reviews = data.reduce((reviews, product) => [
6201
6504
  ...reviews,
6202
6505
  ...product.reviews.map((review) => (Object.assign(Object.assign({}, review), { reviewStatus: this.getReviewStatus(review), productId: product.id, productName: product.name, productSku: product.sku }))),
6203
6506
  ], []);
6204
- }
6205
- async fetchReviews(status) {
6507
+ let filteredReviews = reviews;
6508
+ if (filters.sku) {
6509
+ filteredReviews = filteredReviews.filter((review) => review.productSku === filters.sku);
6510
+ }
6511
+ if (filters.status) {
6512
+ filteredReviews = filteredReviews.filter((review) => review.reviewStatus === filters.status);
6513
+ }
6514
+ if (filters.email) {
6515
+ filteredReviews = filteredReviews.filter((review) => review.email === filters.email);
6516
+ }
6517
+ if (filters.rate) {
6518
+ filteredReviews = filteredReviews.filter((review) => review.rate === filters.rate);
6519
+ }
6520
+ if (filters.period) {
6521
+ filteredReviews = filteredReviews.filter((review) => {
6522
+ const reviewDate = new Date(review.createdAt);
6523
+ return reviewDate >= filters.period.start && reviewDate <= filters.period.end;
6524
+ });
6525
+ }
6526
+ if (((_c = this.cache) === null || _c === void 0 ? void 0 : _c.cacheAdapter) && ((_d = options === null || options === void 0 ? void 0 : options.cache) === null || _d === void 0 ? void 0 : _d.enabled)) {
6527
+ const cacheKey = `${this.model.name.toLowerCase()}:all-reviews:${MD5GeneratorHelper.generateMD5(filters)}`;
6528
+ await this.cache.cacheAdapter.set({
6529
+ key: cacheKey,
6530
+ data: JSON.stringify(filteredReviews),
6531
+ expirationInSeconds: ((_e = options === null || options === void 0 ? void 0 : options.cache) === null || _e === void 0 ? void 0 : _e.ttl) || this.cache.ttlDefault,
6532
+ });
6533
+ this.logger.log(`Dados salvos no cache: ${cacheKey}`);
6534
+ }
6535
+ return filteredReviews;
6536
+ }
6537
+ async fetchReviews(status, options) {
6538
+ var _a, _b, _c, _d, _e;
6539
+ if (((_a = this.cache) === null || _a === void 0 ? void 0 : _a.cacheAdapter) && ((_b = options === null || options === void 0 ? void 0 : options.cache) === null || _b === void 0 ? void 0 : _b.enabled)) {
6540
+ const cacheKey = `${this.model.name.toLowerCase()}:reviews:${status}`;
6541
+ const cachedData = await this.cache.cacheAdapter.get(cacheKey);
6542
+ if (cachedData) {
6543
+ this.logger.log(`Dados recuperados do cache: ${cacheKey}`);
6544
+ return JSON.parse(cachedData);
6545
+ }
6546
+ }
6206
6547
  const reviewsExpression = {
6207
6548
  status: status === 'pending'
6208
6549
  ? { [HasuraGraphQLWhere.ISNULL]: true }
@@ -6211,7 +6552,7 @@ class ProductHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGra
6211
6552
  const { product: data } = await this.query('product', ['id', 'name', 'sku', { reviews: { columnName: 'reviews', fields: this.reviewsFields } }], {
6212
6553
  where: { value: { reviews: reviewsExpression }, type: 'product_bool_exp', required: true },
6213
6554
  });
6214
- return data.reduce((reviews, product) => [
6555
+ const reviews = data.reduce((reviews, product) => [
6215
6556
  ...reviews,
6216
6557
  ...product.reviews
6217
6558
  .filter((review) => (status === 'pending' && [undefined, null].includes(review.status)) ||
@@ -6219,9 +6560,20 @@ class ProductHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGra
6219
6560
  (status === 'rejected' && review.status === false))
6220
6561
  .map((review) => (Object.assign(Object.assign({}, this.bindReviewToModel(review)), { productId: product.id, productName: product.name, productSku: product.sku }))),
6221
6562
  ], []);
6563
+ if (((_c = this.cache) === null || _c === void 0 ? void 0 : _c.cacheAdapter) && ((_d = options === null || options === void 0 ? void 0 : options.cache) === null || _d === void 0 ? void 0 : _d.enabled)) {
6564
+ const cacheKey = `${this.model.name.toLowerCase()}:reviews:${status}`;
6565
+ await this.cache.cacheAdapter.set({
6566
+ key: cacheKey,
6567
+ data: JSON.stringify(reviews),
6568
+ expirationInSeconds: ((_e = options === null || options === void 0 ? void 0 : options.cache) === null || _e === void 0 ? void 0 : _e.ttl) || this.cache.ttlDefault,
6569
+ });
6570
+ this.logger.log(`Dados salvos no cache: ${cacheKey}`);
6571
+ }
6572
+ return reviews;
6222
6573
  }
6223
- async findCatalog(params, mainGender) {
6224
- return this.find(Object.assign(Object.assign({}, params), { filters: Object.assign(Object.assign({}, params.filters), { published: true }), orderBy: Object.assign(Object.assign({ hasStock: 'desc' }, (!mainGender ? {} : { intGender: mainGender === 'female' ? 'desc' : 'asc' })), lodash.omit(params.orderBy, ['hasStock', 'intGender'])) }));
6574
+ async findCatalog(params, mainGender, options) {
6575
+ const result = await this.find(Object.assign(Object.assign({}, params), { filters: Object.assign(Object.assign({}, params.filters), { published: true }), orderBy: Object.assign(Object.assign({ hasStock: 'desc' }, (!mainGender ? {} : { intGender: mainGender === 'female' ? 'desc' : 'asc' })), lodash.omit(params.orderBy, ['hasStock', 'intGender'])) }), options);
6576
+ return result;
6225
6577
  }
6226
6578
  async cleanShoppingCountFromIds(ids) {
6227
6579
  return await this.mutation('update_product', ['affected_rows'], {
@@ -6328,7 +6680,16 @@ class ProductHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGra
6328
6680
  return (_b = data === null || data === void 0 ? void 0 : data[0]) === null || _b === void 0 ? void 0 : _b.id;
6329
6681
  throw new NotFoundError(`Product with id ${id} not found`);
6330
6682
  }
6331
- async findReviewsByProduct(productId) {
6683
+ async findReviewsByProduct(productId, options) {
6684
+ var _a, _b, _c, _d, _e;
6685
+ if (((_a = this.cache) === null || _a === void 0 ? void 0 : _a.cacheAdapter) && ((_b = options === null || options === void 0 ? void 0 : options.cache) === null || _b === void 0 ? void 0 : _b.enabled)) {
6686
+ const cacheKey = `${this.model.name.toLowerCase()}:reviews:product:${productId}`;
6687
+ const cachedData = await this.cache.cacheAdapter.get(cacheKey);
6688
+ if (cachedData) {
6689
+ this.logger.log(`Dados recuperados do cache: ${cacheKey}`);
6690
+ return JSON.parse(cachedData);
6691
+ }
6692
+ }
6332
6693
  const { product_review: data } = await this.query('product_review', this.reviewsFields, {
6333
6694
  where: {
6334
6695
  value: {
@@ -6338,7 +6699,17 @@ class ProductHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGra
6338
6699
  required: true,
6339
6700
  },
6340
6701
  });
6341
- return data && data.map((review) => this.bindReviewToModel(review));
6702
+ const reviews = data && data.map((review) => this.bindReviewToModel(review));
6703
+ if (((_c = this.cache) === null || _c === void 0 ? void 0 : _c.cacheAdapter) && ((_d = options === null || options === void 0 ? void 0 : options.cache) === null || _d === void 0 ? void 0 : _d.enabled) && reviews) {
6704
+ const cacheKey = `${this.model.name.toLowerCase()}:reviews:product:${productId}`;
6705
+ await this.cache.cacheAdapter.set({
6706
+ key: cacheKey,
6707
+ data: JSON.stringify(reviews),
6708
+ expirationInSeconds: ((_e = options === null || options === void 0 ? void 0 : options.cache) === null || _e === void 0 ? void 0 : _e.ttl) || this.cache.ttlDefault,
6709
+ });
6710
+ this.logger.log(`Dados salvos no cache: ${cacheKey}`);
6711
+ }
6712
+ return reviews;
6342
6713
  }
6343
6714
  async findReview(review, productId) {
6344
6715
  if (review.id)
@@ -6424,25 +6795,25 @@ class ProductHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGra
6424
6795
  tslib.__decorate([
6425
6796
  Log(),
6426
6797
  tslib.__metadata("design:type", Function),
6427
- tslib.__metadata("design:paramtypes", [String]),
6798
+ tslib.__metadata("design:paramtypes", [String, Object]),
6428
6799
  tslib.__metadata("design:returntype", Promise)
6429
6800
  ], ProductHasuraGraphQLRepository.prototype, "getBySlug", null);
6430
6801
  tslib.__decorate([
6431
6802
  Log(),
6432
6803
  tslib.__metadata("design:type", Function),
6433
- tslib.__metadata("design:paramtypes", []),
6804
+ tslib.__metadata("design:paramtypes", [Object, Object]),
6434
6805
  tslib.__metadata("design:returntype", Promise)
6435
6806
  ], ProductHasuraGraphQLRepository.prototype, "fetchProductReviews", null);
6436
6807
  tslib.__decorate([
6437
6808
  Log(),
6438
6809
  tslib.__metadata("design:type", Function),
6439
- tslib.__metadata("design:paramtypes", [String]),
6810
+ tslib.__metadata("design:paramtypes", [String, Object]),
6440
6811
  tslib.__metadata("design:returntype", Promise)
6441
6812
  ], ProductHasuraGraphQLRepository.prototype, "fetchReviews", null);
6442
6813
  tslib.__decorate([
6443
6814
  Log(),
6444
6815
  tslib.__metadata("design:type", Function),
6445
- tslib.__metadata("design:paramtypes", [Object, Object]),
6816
+ tslib.__metadata("design:paramtypes", [Object, Object, Object]),
6446
6817
  tslib.__metadata("design:returntype", Promise)
6447
6818
  ], ProductHasuraGraphQLRepository.prototype, "findCatalog", null);
6448
6819
  tslib.__decorate([
@@ -6450,10 +6821,16 @@ tslib.__decorate([
6450
6821
  tslib.__metadata("design:type", Function),
6451
6822
  tslib.__metadata("design:paramtypes", [Array]),
6452
6823
  tslib.__metadata("design:returntype", Promise)
6453
- ], ProductHasuraGraphQLRepository.prototype, "cleanShoppingCountFromIds", null);
6824
+ ], ProductHasuraGraphQLRepository.prototype, "cleanShoppingCountFromIds", null);
6825
+ tslib.__decorate([
6826
+ Log(),
6827
+ tslib.__metadata("design:type", Function),
6828
+ tslib.__metadata("design:paramtypes", [Number, Object]),
6829
+ tslib.__metadata("design:returntype", Promise)
6830
+ ], ProductHasuraGraphQLRepository.prototype, "findReviewsByProduct", null);
6454
6831
 
6455
6832
  class ProductReviewHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGraphQL(Base)) {
6456
- constructor({ endpoint, authOptions, interceptors, }) {
6833
+ constructor({ endpoint, authOptions, interceptors, cache, }) {
6457
6834
  super({
6458
6835
  tableName: 'product_review',
6459
6836
  model: ProductReview,
@@ -6477,6 +6854,7 @@ class ProductReviewHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHas
6477
6854
  { createdAt: { columnName: 'created_at' } },
6478
6855
  { updatedAt: { columnName: 'updated_at' } },
6479
6856
  ],
6857
+ cache,
6480
6858
  });
6481
6859
  }
6482
6860
  async updateManyStatus(reviews) {
@@ -6518,13 +6896,14 @@ tslib.__decorate([
6518
6896
  ], ProductReviewHasuraGraphQLRepository.prototype, "disaproveReview", null);
6519
6897
 
6520
6898
  class ProductStockNotificationHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGraphQL(Base)) {
6521
- constructor({ endpoint, authOptions, interceptors, }) {
6899
+ constructor({ endpoint, authOptions, interceptors, cache, }) {
6522
6900
  super({
6523
6901
  tableName: 'product_stock_notification',
6524
6902
  model: ProductStockNotification,
6525
6903
  endpoint,
6526
6904
  authOptions,
6527
6905
  interceptors,
6906
+ cache,
6528
6907
  fields: [
6529
6908
  'id',
6530
6909
  { productId: { columnName: 'product_id' } },
@@ -6579,13 +6958,14 @@ class ProductStockNotificationHasuraGraphQLRepository extends withCrudHasuraGrap
6579
6958
  }
6580
6959
 
6581
6960
  class VariantHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGraphQL(Base)) {
6582
- constructor({ endpoint, authOptions, interceptors, }) {
6961
+ constructor({ endpoint, authOptions, interceptors, cache, }) {
6583
6962
  super({
6584
6963
  tableName: 'product',
6585
6964
  model: VariantHasuraGraphQL,
6586
6965
  endpoint,
6587
6966
  authOptions,
6588
6967
  interceptors,
6968
+ cache,
6589
6969
  fields: [
6590
6970
  { id: { columnName: 'id', to: (value) => +value, from: (value) => value.toString() } },
6591
6971
  { firestoreId: { columnName: 'firestore_id' } },
@@ -6692,13 +7072,14 @@ class WishlistHasuraGraphQL extends Wishlist {
6692
7072
  }
6693
7073
 
6694
7074
  class WishlistHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGraphQL(Base)) {
6695
- constructor({ endpoint, authOptions, interceptors, }, categoryProductRepository) {
7075
+ constructor({ endpoint, authOptions, interceptors, cache, }, categoryProductRepository) {
6696
7076
  super({
6697
7077
  tableName: 'category',
6698
7078
  model: WishlistHasuraGraphQL,
6699
7079
  endpoint,
6700
7080
  authOptions,
6701
7081
  interceptors,
7082
+ cache,
6702
7083
  fields: [
6703
7084
  { id: { columnName: 'id', to: (value) => +value, from: (value) => value.toString() } },
6704
7085
  { firestoreId: { columnName: 'firestore_id' } },
@@ -7651,8 +8032,6 @@ exports.ProductErrorsHasuraGraphQLRepository = ProductErrorsHasuraGraphQLReposit
7651
8032
  exports.ProductFirestoreRepository = ProductFirestoreRepository;
7652
8033
  exports.ProductHasuraGraphQL = ProductHasuraGraphQL;
7653
8034
  exports.ProductHasuraGraphQLRepository = ProductHasuraGraphQLRepository;
7654
- exports.ProductQueue = ProductQueue;
7655
- exports.ProductQueueFirestoreRepository = ProductQueueFirestoreRepository;
7656
8035
  exports.ProductReview = ProductReview;
7657
8036
  exports.ProductReviewHasuraGraphQLRepository = ProductReviewHasuraGraphQLRepository;
7658
8037
  exports.ProductStockNotification = ProductStockNotification;
@@ -7665,6 +8044,7 @@ exports.ReflectHelper = ReflectHelper;
7665
8044
  exports.Register = Register;
7666
8045
  exports.RegisterFirebaseAuthService = RegisterFirebaseAuthService;
7667
8046
  exports.RequiredArgumentError = RequiredArgumentError;
8047
+ exports.RestCacheAdapter = RestCacheAdapter;
7668
8048
  exports.RoundProductPricesHelper = RoundProductPricesHelper;
7669
8049
  exports.Sequence = Sequence;
7670
8050
  exports.SequenceFirestoreRepository = SequenceFirestoreRepository;