@infrab4a/connect 4.25.0-beta.1 → 4.25.0-beta.11

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 +1004 -608
  2. package/index.esm.js +1005 -608
  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 +20 -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 -15
  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.esm.js CHANGED
@@ -3,12 +3,13 @@ import { __values, __spreadArray, __read, __extends, __decorate, __metadata, __r
3
3
  import { plainToInstance, instanceToPlain, Type } from 'class-transformer';
4
4
  import { parseISO, format, startOfDay, endOfDay, subDays, addDays } from 'date-fns';
5
5
  export { add, addBusinessDays, addDays, addMonths, addYears, endOfDay, format, formatISO9075, parseISO, startOfDay, sub, subDays } from 'date-fns';
6
- import { isNil, isArray, first, last, flatten, compact, get, isString, each, unset, isObject, set, isNumber, chunk, isEmpty, isDate, isBoolean, isInteger, isNaN as isNaN$1, sortBy, omit } from 'lodash';
6
+ import { isNil, isArray, first, last, flatten, compact, get, isString, each, unset, isObject, isEmpty, isDate, set, isNumber, chunk, isBoolean, isInteger, isNaN as isNaN$1, sortBy, omit } from 'lodash';
7
7
  export { chunk, each, get, isBoolean, isDate, isEmpty, isInteger, isNaN, isNil, isNumber, isObject, isString, now, omit, pick, set, sortBy, unset } from 'lodash';
8
8
  import { debug } from 'debug';
9
9
  import { CustomError } from 'ts-custom-error';
10
10
  import axios, { AxiosError } from 'axios';
11
11
  import { signInWithEmailAndPassword, signInWithPopup, GoogleAuthProvider, signInAnonymously, sendPasswordResetEmail, createUserWithEmailAndPassword, sendEmailVerification } from 'firebase/auth';
12
+ import { Md5 } from 'ts-md5';
12
13
  import { deleteField, arrayUnion, arrayRemove, Timestamp, doc, getDoc, updateDoc, setDoc, deleteDoc, collection, limit, getDocs, query, where, orderBy, startAfter, addDoc } from 'firebase/firestore';
13
14
  import { ref, uploadBytes } from 'firebase/storage';
14
15
  import { mutation, query as query$1 } from 'gql-query-builder';
@@ -2552,6 +2553,7 @@ class GlampointsPaymentService {
2552
2553
  console.error('[rewards - rewardByOrder] reward request error', error.response.status, JSON.stringify(error.response.data.message), order.orderNumber);
2553
2554
  else
2554
2555
  console.log(JSON.stringify(error));
2556
+ throw new Error(`Reward errors: ${error.response.data.message}`);
2555
2557
  }
2556
2558
  }
2557
2559
  async negativateRewardByOrderId(order) {
@@ -2604,12 +2606,6 @@ class LogDocument extends BaseModel {
2604
2606
  }
2605
2607
  }
2606
2608
 
2607
- class ProductQueue extends BaseModel {
2608
- static get identifiersFields() {
2609
- return ['id'];
2610
- }
2611
- }
2612
-
2613
2609
  class Sequence extends BaseModel {
2614
2610
  static get identifiersFields() {
2615
2611
  return ['id'];
@@ -2833,6 +2829,71 @@ class AdyenCardAxiosAdapter {
2833
2829
  }
2834
2830
  }
2835
2831
 
2832
+ class RestCacheAdapter {
2833
+ constructor(config) {
2834
+ this.logger = new DebugHelper('RestCacheAdapter');
2835
+ this.client = axios.create({
2836
+ baseURL: config.baseURL,
2837
+ headers: Object.assign(Object.assign({ 'Content-Type': 'application/json' }, (isNil(config.authToken) ? {} : { Authorization: `Bearer ${config.authToken}` })), (isNil(config.mobileApiKey) ? {} : { 'X-Mobile-API-Key': config.mobileApiKey })),
2838
+ });
2839
+ }
2840
+ async set(options) {
2841
+ try {
2842
+ const response = await this.client.post('/redis/set', {
2843
+ key: options.key,
2844
+ data: options.data,
2845
+ ex: options.expirationInSeconds,
2846
+ });
2847
+ return response.data.success;
2848
+ }
2849
+ catch (error) {
2850
+ if (error instanceof Error)
2851
+ this.logger.error(new Error(`[RestCacheAdapter] Erro ao definir cache: ${error.message}`));
2852
+ return false;
2853
+ }
2854
+ }
2855
+ async get(key) {
2856
+ try {
2857
+ const response = await this.client.post('/redis/get', {
2858
+ key,
2859
+ });
2860
+ if (response.data.success) {
2861
+ return response.data.data;
2862
+ }
2863
+ return null;
2864
+ }
2865
+ catch (error) {
2866
+ if (error instanceof Error)
2867
+ this.logger.error(new Error(`[RestCacheAdapter] Erro ao recuperar cache: ${error.message}`));
2868
+ return null;
2869
+ }
2870
+ }
2871
+ async remove(key) {
2872
+ try {
2873
+ const response = await this.client.post('/redis/del', {
2874
+ key,
2875
+ });
2876
+ return response.data.success;
2877
+ }
2878
+ catch (error) {
2879
+ if (error instanceof Error)
2880
+ this.logger.error(new Error(`[RestCacheAdapter] Erro ao remover cache: ${error.message}`));
2881
+ return false;
2882
+ }
2883
+ }
2884
+ async clear() {
2885
+ try {
2886
+ const response = await this.client.post('/redis/flushdb', {});
2887
+ return response.data.success;
2888
+ }
2889
+ catch (error) {
2890
+ if (error instanceof Error)
2891
+ this.logger.error(new Error(`[RestCacheAdapter] Erro ao limpar cache: ${error.message}`));
2892
+ return false;
2893
+ }
2894
+ }
2895
+ }
2896
+
2836
2897
  class AxiosAdapter {
2837
2898
  constructor(config) {
2838
2899
  this.config = config;
@@ -3169,6 +3230,7 @@ const withFirestore = (MixinBase) => {
3169
3230
  this.fields = options.fields;
3170
3231
  this.interceptors = options.interceptors;
3171
3232
  this.logger = DebugHelper.from(this);
3233
+ this.cache = options.cache;
3172
3234
  }
3173
3235
  collection(path) {
3174
3236
  return this.firestore.getCollection(path || this.collectionName).withConverter(this.buildModelInstance());
@@ -3215,123 +3277,487 @@ const withHelpers = (MixinBase) => {
3215
3277
  };
3216
3278
  };
3217
3279
 
3218
- const withGetFirestore = (MixinBase) => {
3219
- return class GetFirestore extends MixinBase {
3220
- async get(identifiers) {
3221
- var _a, _b, _c, _d;
3222
- const logger = this.logger.with('get');
3223
- const collectionName = this.buildCollectionPathForGet(identifiers);
3224
- const instance = this.model.toInstance(this.model.identifiersFields.reduce((acc, field) => (Object.assign(Object.assign({}, acc), { [field]: identifiers[field] })), {}));
3225
- const req = { collection: collectionName, data: identifiers };
3226
- try {
3227
- 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 }));
3228
- const builded = (intercepted === null || intercepted === void 0 ? void 0 : intercepted.instance) || instance;
3229
- const docRef = await this.collection(collectionName)
3230
- .getDoc(Object.values(builded.identifier).shift().toString())
3231
- .get();
3232
- const data = docRef.data();
3233
- if (isNil(data))
3234
- throw new NotFoundError(`Document '${collectionName}/${Object.values(identifiers).shift()}' not found`);
3235
- 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;
3236
- logger.log({ req, res });
3237
- return res;
3238
- }
3239
- catch (error) {
3240
- if (error instanceof Error)
3241
- logger.log({ req, res: error, stack: error.stack });
3242
- throw error;
3243
- }
3244
- }
3245
- buildCollectionPathForGet(identifiers) {
3246
- return this.isSubCollection(this)
3247
- ? `${this.parentRepository.collectionName}/${identifiers[this.parentIdField]}/${this.collectionName}`
3248
- : this.collectionName;
3249
- }
3250
- };
3280
+ class AttributeOptionHelper {
3281
+ }
3282
+ AttributeOptionHelper.FindByAttribute = (attributeName, fields) => {
3283
+ var _a;
3284
+ if (fields.includes(attributeName))
3285
+ return { columnName: attributeName.toString(), attributeName, to: (value) => value, from: (value) => value };
3286
+ const field = fields.find((columnOption) => isObject(columnOption) && Object.keys(columnOption).includes(attributeName.toString()));
3287
+ const fieldOption = (_a = is(field)) === null || _a === void 0 ? void 0 : _a[attributeName];
3288
+ if (isNil(fieldOption))
3289
+ return { columnName: attributeName.toString(), attributeName };
3290
+ if (Array.isArray(fieldOption))
3291
+ return { columnName: attributeName.toString(), attributeName, fields: fieldOption };
3292
+ return Object.assign({ attributeName, columnName: attributeName.toString() }, fieldOption);
3293
+ };
3294
+ AttributeOptionHelper.CheckIsColumnOption = (fieldValue) => !!(fieldValue === null || fieldValue === void 0 ? void 0 : fieldValue.columnName);
3295
+ AttributeOptionHelper.FindColumnOptionFromList = (columnName, fields) => {
3296
+ if (fields.includes(columnName))
3297
+ return { columnName, attributeName: columnName };
3298
+ const field = is(fields.find((field) => {
3299
+ if (!isObject(field))
3300
+ return false;
3301
+ const columnOption = Object.values(field).find((option) => AttributeOptionHelper.CheckIsColumnOption(option) && option.columnName === columnName ? option : {});
3302
+ return AttributeOptionHelper.CheckIsColumnOption(columnOption) && (columnOption === null || columnOption === void 0 ? void 0 : columnOption.columnName) === columnName;
3303
+ }) || {});
3304
+ const attributeName = Object.keys(field).find((fieldOptionFromList) => AttributeOptionHelper.CheckIsColumnOption(field[fieldOptionFromList]) || Array.isArray(field[fieldOptionFromList]));
3305
+ const fieldOption = field === null || field === void 0 ? void 0 : field[attributeName];
3306
+ if (Array.isArray(fieldOption))
3307
+ return { attributeName: attributeName, fields: fieldOption };
3308
+ return Object.assign({ attributeName: attributeName || columnName, columnName }, fieldOption);
3251
3309
  };
3252
3310
 
3253
- var FirestoreFieldType;
3254
- (function (FirestoreFieldType) {
3255
- FirestoreFieldType["String"] = "string";
3256
- FirestoreFieldType["Number"] = "number";
3257
- FirestoreFieldType["Boolean"] = "boolean";
3258
- FirestoreFieldType["Timestamp"] = "timestamp";
3259
- FirestoreFieldType["Array"] = "array";
3260
- FirestoreFieldType["Map"] = "map";
3261
- })(FirestoreFieldType || (FirestoreFieldType = {}));
3311
+ var HasuraGraphQLWhere;
3312
+ (function (HasuraGraphQLWhere) {
3313
+ HasuraGraphQLWhere["EQUALS"] = "_eq";
3314
+ HasuraGraphQLWhere["GT"] = "_gt";
3315
+ HasuraGraphQLWhere["GTE"] = "_gte";
3316
+ HasuraGraphQLWhere["IN"] = "_in";
3317
+ HasuraGraphQLWhere["NOTIN"] = "_nin";
3318
+ HasuraGraphQLWhere["LT"] = "_lt";
3319
+ HasuraGraphQLWhere["LTE"] = "_lte";
3320
+ HasuraGraphQLWhere["LIKE"] = "_like";
3321
+ HasuraGraphQLWhere["ILIKE"] = "_ilike";
3322
+ HasuraGraphQLWhere["NOTLIKE"] = "_nlike";
3323
+ HasuraGraphQLWhere["ISNULL"] = "_is_null";
3324
+ HasuraGraphQLWhere["ISNOTNULL"] = "_is_null";
3325
+ HasuraGraphQLWhere["JSON_CONTAINS"] = "_contains";
3326
+ HasuraGraphQLWhere["JSON_HAS_KEYS_ANY"] = "_has_keys_any";
3327
+ HasuraGraphQLWhere["IREGEX"] = "_iregex";
3328
+ HasuraGraphQLWhere["REGEX"] = "_regex";
3329
+ })(HasuraGraphQLWhere || (HasuraGraphQLWhere = {}));
3262
3330
 
3263
- const withFindFirestore = (MixinBase) => {
3264
- const checkIfIsFilterOption = (filter) => !isNil(filter === null || filter === void 0 ? void 0 : filter.operator);
3265
- const getValueFromFilter = (filter) => {
3266
- return checkIfIsFilterOption(filter) ? filter.value : filter;
3267
- };
3268
- return class FindFirestore extends MixinBase {
3269
- constructor() {
3270
- super(...arguments);
3271
- this.makeFirestoreWhere = (filter) => Object.keys(filter).reduce((queries, fieldName) => [
3272
- ...queries,
3273
- ...this.buildWhereSentence(fieldName, is(filter[fieldName])),
3274
- ], []);
3275
- this.buildWhereSentence = (fieldName, options) => {
3276
- var _a, _b, _c, _d;
3277
- if (this.isSubCollection(this) && fieldName === this.parentIdField)
3278
- return [];
3279
- const value = (options === null || options === void 0 ? void 0 : options.value) || options;
3280
- const object = {};
3281
- set(object, fieldName, value);
3282
- const plainInstance = new this.model(object).toPlain();
3283
- const firestoreFieldName = fieldName.toString().indexOf('.') > -1
3284
- ? fieldName.toString()
3285
- : Object.keys(plainInstance).find((key) => plainInstance[key]);
3286
- if ((options === null || options === void 0 ? void 0 : options.operator) === Where.LIKE) {
3287
- if (Array.isArray(options === null || options === void 0 ? void 0 : options.value) &&
3288
- (((_a = this.fields) === null || _a === void 0 ? void 0 : _a[firestoreFieldName]) ===
3289
- FirestoreFieldType.Array ||
3290
- !((_b = this.fields) === null || _b === void 0 ? void 0 : _b[firestoreFieldName])))
3291
- return [[firestoreFieldName, 'array-contains-any', options.value]];
3292
- return [
3293
- [firestoreFieldName, '>=', options.value],
3294
- [firestoreFieldName, '<=', `${options.value}~`],
3295
- ];
3296
- }
3297
- if ((options === null || options === void 0 ? void 0 : options.operator) === Where.IN &&
3298
- Array.isArray(options === null || options === void 0 ? void 0 : options.value) &&
3299
- (((_c = this.fields) === null || _c === void 0 ? void 0 : _c[firestoreFieldName]) ===
3300
- FirestoreFieldType.Array ||
3301
- !((_d = this.fields) === null || _d === void 0 ? void 0 : _d[firestoreFieldName])))
3302
- return [[firestoreFieldName, 'array-contains', options.value]];
3303
- if (isObject(options) && isNil(options === null || options === void 0 ? void 0 : options.operator) && isNil(options === null || options === void 0 ? void 0 : options.value)) {
3304
- return Object.keys(options).reduce((queries, key) => [
3305
- ...queries,
3306
- ...this.buildWhereSentence(`${fieldName.toString()}.${key}`, is(options)[key]),
3307
- ], []);
3308
- }
3309
- return [[firestoreFieldName, ((options === null || options === void 0 ? void 0 : options.operator) || '=='), (options === null || options === void 0 ? void 0 : options.value) || options]];
3310
- };
3311
- this.makeFirestoreOrderBy = (filters, fieldsToOrderBy) => {
3312
- const orderByKeys = Object.keys(fieldsToOrderBy || {});
3313
- if (!orderByKeys.length)
3314
- return [];
3315
- const filtersKeysWithUnordered = Object.keys(filters || {}).filter((filterKey) => !orderByKeys.includes(filterKey));
3316
- if (filtersKeysWithUnordered.length)
3317
- filtersKeysWithUnordered.forEach((filterKey) => (fieldsToOrderBy = Object.assign(Object.assign({}, (![Where.EQUALS].includes(is(filters[filterKey]).operator)
3318
- ? { [filterKey]: 'asc' }
3319
- : {})), fieldsToOrderBy)));
3320
- return Object.keys(fieldsToOrderBy).map((fieldName) => [
3321
- fieldName,
3322
- fieldsToOrderBy[fieldName],
3323
- ]);
3331
+ var HasuraGraphQLColumnType;
3332
+ (function (HasuraGraphQLColumnType) {
3333
+ HasuraGraphQLColumnType["Int"] = "Int";
3334
+ HasuraGraphQLColumnType["Float"] = "Float";
3335
+ HasuraGraphQLColumnType["Boolean"] = "Boolean";
3336
+ HasuraGraphQLColumnType["String"] = "String";
3337
+ HasuraGraphQLColumnType["DateTime"] = "timestampz";
3338
+ HasuraGraphQLColumnType["Json"] = "json";
3339
+ HasuraGraphQLColumnType["Jsonb"] = "jsonb";
3340
+ HasuraGraphQLColumnType["Enum"] = "enum";
3341
+ HasuraGraphQLColumnType["Uuid"] = "uuid";
3342
+ })(HasuraGraphQLColumnType || (HasuraGraphQLColumnType = {}));
3343
+
3344
+ class FilterOptionHelper {
3345
+ }
3346
+ FilterOptionHelper.CheckIfIsFilterOption = (filter) => !isNil(filter === null || filter === void 0 ? void 0 : filter.operator);
3347
+ FilterOptionHelper.GetValueFromFilter = (filter, fieldOption) => {
3348
+ if (!FilterOptionHelper.CheckIfIsFilterOption(filter))
3349
+ return filter;
3350
+ if (filter.operator === Where.ISNULL)
3351
+ return true;
3352
+ if (filter.operator === Where.ISNOTNULL)
3353
+ return false;
3354
+ const converter = fieldOption.to
3355
+ ? fieldOption.to
3356
+ : (value) => filter.operator === Where.LIKE && !Array.isArray(filter.value) && value.indexOf('%') < 0
3357
+ ? `%${value}%`
3358
+ : value;
3359
+ const converterResult = Array.isArray(filter.value) && !fieldOption.fields && [Where.IN, Where.NOTIN].includes(filter.operator)
3360
+ ? filter.value.map((fieldValue) => converter(fieldValue))
3361
+ : converter(filter.value);
3362
+ const newValue = filter.ignoreCase && !filter.ignoreAccent && !Array.isArray(filter.value) && converterResult.indexOf('%') < 0
3363
+ ? `%${converterResult}%`
3364
+ : converterResult;
3365
+ return filter.ignoreAccent && !Array.isArray(filter.value)
3366
+ ? FilterOptionHelper.buildInsensitiveSentence(newValue)
3367
+ : newValue;
3368
+ };
3369
+ FilterOptionHelper.buildInsensitiveSentence = (value) => {
3370
+ const valueWithoutAccents = FilterOptionHelper.removeAccents(value);
3371
+ let result = '';
3372
+ for (const char of valueWithoutAccents) {
3373
+ const allCharOptions = [];
3374
+ if (['a', 'e', 'i', 'o', 'u', 'c', 'A', 'E', 'I', 'O', 'U', 'C'].includes(char)) {
3375
+ const charOptions = {
3376
+ a: ['á', 'â', 'ã', 'à', 'a'],
3377
+ e: ['é', 'ê', 'ẽ', 'è', 'e'],
3378
+ i: ['í', 'î', 'ĩ', 'ì', 'i'],
3379
+ o: ['ó', 'ô', 'õ', 'ò', 'o'],
3380
+ u: ['ú', 'û', 'ũ', 'ù', 'u'],
3381
+ c: ['ç', 'c'],
3382
+ A: ['Á', 'Â', 'Ã', 'À', 'A'],
3383
+ E: ['É', 'Ê', 'Ẽ', 'È', 'E'],
3384
+ I: ['Í', 'Î', 'Ĩ', 'Ì', 'I'],
3385
+ O: ['Ó', 'Ô', 'Õ', 'Ò', 'O'],
3386
+ U: ['Ú', 'Û', 'Ũ', 'Ù', 'U'],
3387
+ C: ['Ç', 'C'],
3324
3388
  };
3389
+ allCharOptions.push(...charOptions[char]);
3390
+ result += `[${allCharOptions.join('')}]`;
3325
3391
  }
3326
- async find(find = {}) {
3327
- var _a, _b, _c, _d, _e, _f;
3328
- const logger = this.logger.with('find');
3329
- const collectionName = this.buildCollectionPathForFind(find.filters);
3330
- const collection = this.collection(collectionName);
3331
- 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;
3392
+ else {
3393
+ result += char;
3394
+ }
3395
+ }
3396
+ return result;
3397
+ };
3398
+ FilterOptionHelper.removeAccents = (text) => {
3399
+ return text.normalize('NFD').replace(/[\u0300-\u036f]/g, '');
3400
+ };
3401
+
3402
+ class BindFilterQueryHelper {
3403
+ }
3404
+ BindFilterQueryHelper.MakeGraphQLWhere = (filter, fields) => Object.keys(filter).reduce((variables, fieldName) => {
3405
+ const columnOption = AttributeOptionHelper.FindByAttribute(fieldName, fields);
3406
+ if (!columnOption.bindFindFilter)
3407
+ return Object.assign(Object.assign({}, variables), {
3408
+ [columnOption.columnName]: BindFilterQueryHelper.BuildWhereSentence(fieldName, filter[fieldName], fields),
3409
+ });
3410
+ const builtFilter = columnOption.bindFindFilter(filter[fieldName]);
3411
+ return Object.assign(Object.assign({}, variables), Object.keys(builtFilter).reduce((variablesList, columnName) => (Object.assign(Object.assign({}, variablesList), { [columnName]: BindFilterQueryHelper.BuildWhereSentence(fieldName, builtFilter[columnName], fields) })), {}));
3412
+ }, {});
3413
+ BindFilterQueryHelper.BuildWhereSentence = (field, options, fields) => {
3414
+ const fieldSentenceOptions = AttributeOptionHelper.FindByAttribute(field, fields);
3415
+ const isNestedField = !Array.isArray(options) &&
3416
+ isObject(options) &&
3417
+ isNil(options === null || options === void 0 ? void 0 : options.operator) &&
3418
+ isNil(options === null || options === void 0 ? void 0 : options.value) &&
3419
+ isNil(fieldSentenceOptions === null || fieldSentenceOptions === void 0 ? void 0 : fieldSentenceOptions.to);
3420
+ if (isNestedField)
3421
+ return Object.keys(options).reduce((variables, key) => {
3422
+ const fieldOptions = AttributeOptionHelper.FindByAttribute(key, (fieldSentenceOptions === null || fieldSentenceOptions === void 0 ? void 0 : fieldSentenceOptions.fields) || fields);
3423
+ const columnName = fieldOptions.columnName;
3424
+ const columnFields = fieldOptions.fields;
3425
+ 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) });
3426
+ }, {});
3427
+ if (!Array.isArray(options) && !isNil(fieldSentenceOptions.fields))
3428
+ return {
3429
+ [fieldSentenceOptions.fields[0]]: BindFilterQueryHelper.BuildOperatorSentence(options, fieldSentenceOptions),
3430
+ };
3431
+ if (!Array.isArray(options) && isObject(options) && !FilterOptionHelper.CheckIfIsFilterOption(options))
3432
+ options = Object.values(options)[0];
3433
+ return Array.isArray(options)
3434
+ ? options.reduce((whereSentence, option) => (Object.assign(Object.assign({}, whereSentence), BindFilterQueryHelper.BuildOperatorSentence(option, fieldSentenceOptions))), {})
3435
+ : BindFilterQueryHelper.BuildOperatorSentence(options, fieldSentenceOptions);
3436
+ };
3437
+ BindFilterQueryHelper.BuildOperatorSentence = (options, fieldOption) => ({
3438
+ [BindFilterQueryHelper.GetHasuraOperator(options, fieldOption)]: FilterOptionHelper.GetValueFromFilter(options, fieldOption),
3439
+ });
3440
+ BindFilterQueryHelper.GetHasuraOperator = (options, fieldOption) => FilterOptionHelper.CheckIfIsFilterOption(options)
3441
+ ? fieldOption.type === HasuraGraphQLColumnType.Jsonb
3442
+ ? BindFilterQueryHelper.GetHasuraJsonbOperator(options)
3443
+ : options.operator === Where.LIKE && options.ignoreCase && options.ignoreAccent
3444
+ ? HasuraGraphQLWhere.IREGEX
3445
+ : options.operator === Where.LIKE && options.ignoreAccent
3446
+ ? HasuraGraphQLWhere.REGEX
3447
+ : options.operator === Where.LIKE && options.ignoreCase
3448
+ ? HasuraGraphQLWhere.ILIKE
3449
+ : HasuraGraphQLWhere[Object.keys(HasuraGraphQLWhere).find((graphQLOperator) => graphQLOperator ===
3450
+ Object.keys(Where).find((operator) => Where[operator] === (options === null || options === void 0 ? void 0 : options.operator)))]
3451
+ : HasuraGraphQLWhere.EQUALS;
3452
+ BindFilterQueryHelper.GetHasuraJsonbOperator = (options) => options.operator === Where.IN
3453
+ ? HasuraGraphQLWhere.JSON_CONTAINS
3454
+ : options.operator === Where.LIKE
3455
+ ? HasuraGraphQLWhere.JSON_HAS_KEYS_ANY
3456
+ : HasuraGraphQLWhere[Object.keys(HasuraGraphQLWhere).find((graphQLOperator) => graphQLOperator ===
3457
+ Object.keys(Where).find((operator) => Where[operator] === (options === null || options === void 0 ? void 0 : options.operator)))];
3458
+
3459
+ class CacheKeyGeneratorHelper {
3460
+ static generateCacheKeyFromIdentifiers(modelOrModelName, identifiers) {
3461
+ const sortedKeys = Object.keys(identifiers).sort();
3462
+ const keyParts = sortedKeys.map((key) => `${String(key)}:${identifiers[key]}`);
3463
+ const modelName = modelOrModelName.name.toLowerCase();
3464
+ return `${modelName}:get:${keyParts.join(':')}`;
3465
+ }
3466
+ }
3467
+
3468
+ class GraphQLFieldHelper {
3469
+ }
3470
+ GraphQLFieldHelper.CheckIsGraphQLParams = (params) => !isString(params) && Array.isArray(params) && params.length >= 0 && !!params[0].operation;
3471
+ GraphQLFieldHelper.ConvertModelFieldsToGraphQLFields = (fields) => {
3472
+ return fields === null || fields === void 0 ? void 0 : fields.map((field) => {
3473
+ if (isString(field))
3474
+ return field.toString();
3475
+ if (field === 'affected_rows')
3476
+ return field;
3477
+ const fieldName = Object.keys(field).shift();
3478
+ const fieldValue = is(field[fieldName]);
3479
+ if (Array.isArray(fieldValue))
3480
+ return { [fieldName]: GraphQLFieldHelper.ConvertModelFieldsToGraphQLFields(fieldValue) };
3481
+ if (!AttributeOptionHelper.CheckIsColumnOption(fieldValue))
3482
+ return;
3483
+ const isNestedField = !!fieldValue.fields;
3484
+ if (isNestedField)
3485
+ return GraphQLFieldHelper.ConvertNestedFieldsToGraphQLFields(fieldName, fieldValue);
3486
+ return fieldValue.columnName;
3487
+ }).filter((field) => !!field);
3488
+ };
3489
+ GraphQLFieldHelper.ConvertFieldValueFrom = (data, fields) => Object.keys(data).reduce((result, columnName) => {
3490
+ const { attributeName, fields: attributeFields, from, } = AttributeOptionHelper.FindColumnOptionFromList(columnName, fields);
3491
+ if (!!attributeFields && Array.isArray(attributeFields)) {
3492
+ if (Array.isArray(data[columnName]))
3493
+ return Object.assign(Object.assign({}, result), { [attributeName]: from
3494
+ ? from(data[columnName], data)
3495
+ : is(data[columnName]).map((value) => GraphQLFieldHelper.ConvertFieldValueFrom(is(value), attributeFields)) });
3496
+ if (isObject(data[columnName]))
3497
+ return Object.assign(Object.assign({}, result), { [attributeName]: !!from
3498
+ ? from(data[columnName])
3499
+ : GraphQLFieldHelper.ConvertFieldValueFrom(is(data[columnName]), attributeFields) });
3500
+ }
3501
+ if (!!from)
3502
+ return Object.assign(Object.assign({}, result), { [attributeName]: from(data[columnName], data) });
3503
+ return Object.assign(Object.assign({}, result), { [attributeName]: isString(data[columnName]) ? parseDateTime(data[columnName].toString()) : data[columnName] });
3504
+ }, {});
3505
+ GraphQLFieldHelper.ConvertFieldValueTo = (instance, fields, update = false) => {
3506
+ var _a;
3507
+ const data = ((_a = instance.toPlain) === null || _a === void 0 ? void 0 : _a.call(instance)) || instance;
3508
+ return Object.keys(data).reduce((result, attributeName) => {
3509
+ const { columnName, fields: attributeFields, foreignKeyColumn, to, bindPersistData, } = AttributeOptionHelper.FindByAttribute(attributeName, fields);
3510
+ if (bindPersistData)
3511
+ return Object.assign(Object.assign({}, result), bindPersistData(data[attributeName], instance));
3512
+ if (isNil(columnName))
3513
+ return result;
3514
+ if (!!foreignKeyColumn &&
3515
+ !isEmpty(foreignKeyColumn) &&
3516
+ !Object.keys(foreignKeyColumn).filter((key) => { var _a; return !((_a = is(data[attributeName])) === null || _a === void 0 ? void 0 : _a[key]); }).length)
3517
+ return Object.keys(foreignKeyColumn).reduce((object, current) => {
3518
+ var _a;
3519
+ const { columnName: foreignColumnName } = AttributeOptionHelper.FindByAttribute(foreignKeyColumn[current], fields);
3520
+ return Object.assign(Object.assign({}, object), { [foreignColumnName]: (_a = data[attributeName]) === null || _a === void 0 ? void 0 : _a[current] });
3521
+ }, Object.assign({}, result));
3522
+ if (update &&
3523
+ isObject(data[attributeName]) &&
3524
+ !isNil(attributeFields) &&
3525
+ !isDate(data[attributeName]))
3526
+ return result;
3527
+ if (!!columnName &&
3528
+ Array.isArray(attributeFields) &&
3529
+ isObject(data[attributeName])) {
3530
+ const converted = !isNil(columnName) && to
3531
+ ? to(instance[attributeName], instance)
3532
+ : data[attributeName];
3533
+ return Object.assign(Object.assign({}, result), (converted !== undefined
3534
+ ? {
3535
+ [columnName]: {
3536
+ data: instance[attributeName] instanceof BaseModel
3537
+ ? GraphQLFieldHelper.ConvertFieldValueTo(data[attributeName], attributeFields)
3538
+ : converted,
3539
+ },
3540
+ }
3541
+ : {}));
3542
+ }
3543
+ if (!!to)
3544
+ return Object.assign(Object.assign({}, result), { [columnName]: to(instance[attributeName], instance) });
3545
+ return Object.assign(Object.assign({}, result), { [columnName]: data[attributeName] });
3546
+ }, {});
3547
+ };
3548
+ GraphQLFieldHelper.ConvertNestedFieldsToGraphQLFields = (fieldName, fieldValue) => {
3549
+ const hasCustomFilters = !!fieldValue.filters;
3550
+ if (hasCustomFilters)
3551
+ return {
3552
+ operation: fieldValue.columnName || fieldName,
3553
+ fields: GraphQLFieldHelper.ConvertModelFieldsToGraphQLFields(fieldValue.fields),
3554
+ variables: {
3555
+ [`${fieldValue.columnName}_where`]: {
3556
+ name: 'where',
3557
+ type: fieldValue.filters.filterType,
3558
+ value: BindFilterQueryHelper.MakeGraphQLWhere(fieldValue.filters.filters, fieldValue.fields),
3559
+ required: true,
3560
+ },
3561
+ },
3562
+ };
3563
+ return {
3564
+ [fieldValue.columnName || fieldName]: GraphQLFieldHelper.ConvertModelFieldsToGraphQLFields(fieldValue.fields),
3565
+ };
3566
+ };
3567
+
3568
+ class MD5GeneratorHelper {
3569
+ static generateMD5(data) {
3570
+ if (data === null || data === undefined)
3571
+ return Md5.hashStr('null');
3572
+ const normalizedData = this.normalizeData(data);
3573
+ const jsonString = JSON.stringify(normalizedData);
3574
+ return Md5.hashStr(jsonString);
3575
+ }
3576
+ static normalizeData(data, depth = 0, maxDepth = 100) {
3577
+ if (depth > maxDepth)
3578
+ return '[MAX_DEPTH_REACHED]';
3579
+ if (data === null || data === undefined)
3580
+ return null;
3581
+ if (typeof data !== 'object')
3582
+ return data;
3583
+ if (Array.isArray(data))
3584
+ return data
3585
+ .map((item) => this.normalizeData(item, depth + 1, maxDepth))
3586
+ .sort((a, b) => {
3587
+ const strA = typeof a === 'object' && a !== null ? JSON.stringify(a) : String(a);
3588
+ const strB = typeof b === 'object' && b !== null ? JSON.stringify(b) : String(b);
3589
+ return strA.localeCompare(strB);
3590
+ });
3591
+ const sortedObj = {};
3592
+ const keys = Object.keys(data).sort();
3593
+ keys.forEach((key) => {
3594
+ const value = data[key];
3595
+ sortedObj[key] = this.normalizeData(value, depth + 1, maxDepth);
3596
+ });
3597
+ return sortedObj;
3598
+ }
3599
+ }
3600
+
3601
+ class FirestoreCacheKeyGeneratorHelper {
3602
+ static generateGetCacheKey(model, identifiers) {
3603
+ const sortedEntries = Object.entries(identifiers).sort(([keyA], [keyB]) => keyA.localeCompare(keyB));
3604
+ const keyParts = [];
3605
+ for (const [key, value] of sortedEntries) {
3606
+ keyParts.push(`${key}:${value}`);
3607
+ }
3608
+ return `${model.name.toLowerCase()}:get:${keyParts.join(':')}`;
3609
+ }
3610
+ static generateFindCacheKey(model, findParams) {
3611
+ const md5 = MD5GeneratorHelper.generateMD5(findParams);
3612
+ return `${model.name.toLowerCase()}:find:${md5}`;
3613
+ }
3614
+ }
3615
+
3616
+ const withGetFirestore = (MixinBase) => {
3617
+ return class GetFirestore extends MixinBase {
3618
+ async get(identifiers, options) {
3619
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j;
3620
+ const logger = this.logger.with('get');
3621
+ const collectionName = this.buildCollectionPathForGet(identifiers);
3622
+ const instance = this.model.toInstance(this.model.identifiersFields.reduce((acc, field) => (Object.assign(Object.assign({}, acc), { [field]: identifiers[field] })), {}));
3623
+ const req = { collection: collectionName, data: identifiers };
3624
+ 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) {
3625
+ const cacheKey = FirestoreCacheKeyGeneratorHelper.generateGetCacheKey(this.model, identifiers);
3626
+ const cachedData = await this.cache.cacheAdapter.get(cacheKey);
3627
+ if (cachedData) {
3628
+ logger.log({ req, res: 'Dados recuperados do cache', cacheKey });
3629
+ return this.model.toInstance(JSON.parse(cachedData));
3630
+ }
3631
+ }
3632
+ try {
3633
+ 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 }));
3634
+ const builded = (intercepted === null || intercepted === void 0 ? void 0 : intercepted.instance) || instance;
3635
+ const docRef = await this.collection(collectionName)
3636
+ .getDoc(Object.values(builded.identifier).shift().toString())
3637
+ .get();
3638
+ const data = docRef.data();
3639
+ if (isNil(data))
3640
+ throw new NotFoundError(`Document '${collectionName}/${Object.values(identifiers).shift()}' not found`);
3641
+ 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;
3642
+ logger.log({ req, res });
3643
+ 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) {
3644
+ const cacheKey = FirestoreCacheKeyGeneratorHelper.generateGetCacheKey(this.model, identifiers);
3645
+ await this.cache.cacheAdapter.set({
3646
+ key: cacheKey,
3647
+ data: JSON.stringify((res === null || res === void 0 ? void 0 : res.toPlain()) || res),
3648
+ expirationInSeconds: ((_j = options === null || options === void 0 ? void 0 : options.cache) === null || _j === void 0 ? void 0 : _j.ttl) || this.cache.ttlDefault,
3649
+ });
3650
+ logger.log({ req, message: 'Dados salvos no cache', cacheKey });
3651
+ }
3652
+ return res;
3653
+ }
3654
+ catch (error) {
3655
+ if (error instanceof Error)
3656
+ logger.log({ req, res: error, stack: error.stack });
3657
+ throw error;
3658
+ }
3659
+ }
3660
+ buildCollectionPathForGet(identifiers) {
3661
+ return this.isSubCollection(this)
3662
+ ? `${this.parentRepository.collectionName}/${identifiers[this.parentIdField]}/${this.collectionName}`
3663
+ : this.collectionName;
3664
+ }
3665
+ };
3666
+ };
3667
+
3668
+ var FirestoreFieldType;
3669
+ (function (FirestoreFieldType) {
3670
+ FirestoreFieldType["String"] = "string";
3671
+ FirestoreFieldType["Number"] = "number";
3672
+ FirestoreFieldType["Boolean"] = "boolean";
3673
+ FirestoreFieldType["Timestamp"] = "timestamp";
3674
+ FirestoreFieldType["Array"] = "array";
3675
+ FirestoreFieldType["Map"] = "map";
3676
+ })(FirestoreFieldType || (FirestoreFieldType = {}));
3677
+
3678
+ const withFindFirestore = (MixinBase) => {
3679
+ const checkIfIsFilterOption = (filter) => !isNil(filter === null || filter === void 0 ? void 0 : filter.operator);
3680
+ const getValueFromFilter = (filter) => {
3681
+ return checkIfIsFilterOption(filter) ? filter.value : filter;
3682
+ };
3683
+ return class FindFirestore extends MixinBase {
3684
+ constructor() {
3685
+ super(...arguments);
3686
+ this.makeFirestoreWhere = (filter) => Object.keys(filter).reduce((queries, fieldName) => [
3687
+ ...queries,
3688
+ ...this.buildWhereSentence(fieldName, is(filter[fieldName])),
3689
+ ], []);
3690
+ this.buildWhereSentence = (fieldName, options) => {
3691
+ var _a, _b, _c, _d;
3692
+ if (this.isSubCollection(this) && fieldName === this.parentIdField)
3693
+ return [];
3694
+ const value = (options === null || options === void 0 ? void 0 : options.value) || options;
3695
+ const object = {};
3696
+ set(object, fieldName, value);
3697
+ const plainInstance = new this.model(object).toPlain();
3698
+ const firestoreFieldName = fieldName.toString().indexOf('.') > -1
3699
+ ? fieldName.toString()
3700
+ : Object.keys(plainInstance).find((key) => plainInstance[key]);
3701
+ if ((options === null || options === void 0 ? void 0 : options.operator) === Where.LIKE) {
3702
+ if (Array.isArray(options === null || options === void 0 ? void 0 : options.value) &&
3703
+ (((_a = this.fields) === null || _a === void 0 ? void 0 : _a[firestoreFieldName]) ===
3704
+ FirestoreFieldType.Array ||
3705
+ !((_b = this.fields) === null || _b === void 0 ? void 0 : _b[firestoreFieldName])))
3706
+ return [[firestoreFieldName, 'array-contains-any', options.value]];
3707
+ return [
3708
+ [firestoreFieldName, '>=', options.value],
3709
+ [firestoreFieldName, '<=', `${options.value}~`],
3710
+ ];
3711
+ }
3712
+ if ((options === null || options === void 0 ? void 0 : options.operator) === Where.IN &&
3713
+ Array.isArray(options === null || options === void 0 ? void 0 : options.value) &&
3714
+ (((_c = this.fields) === null || _c === void 0 ? void 0 : _c[firestoreFieldName]) ===
3715
+ FirestoreFieldType.Array ||
3716
+ !((_d = this.fields) === null || _d === void 0 ? void 0 : _d[firestoreFieldName])))
3717
+ return [[firestoreFieldName, 'array-contains', options.value]];
3718
+ if (isObject(options) && isNil(options === null || options === void 0 ? void 0 : options.operator) && isNil(options === null || options === void 0 ? void 0 : options.value)) {
3719
+ return Object.keys(options).reduce((queries, key) => [
3720
+ ...queries,
3721
+ ...this.buildWhereSentence(`${fieldName.toString()}.${key}`, is(options)[key]),
3722
+ ], []);
3723
+ }
3724
+ return [[firestoreFieldName, ((options === null || options === void 0 ? void 0 : options.operator) || '=='), (options === null || options === void 0 ? void 0 : options.value) || options]];
3725
+ };
3726
+ this.makeFirestoreOrderBy = (filters, fieldsToOrderBy) => {
3727
+ const orderByKeys = Object.keys(fieldsToOrderBy || {});
3728
+ if (!orderByKeys.length)
3729
+ return [];
3730
+ const filtersKeysWithUnordered = Object.keys(filters || {}).filter((filterKey) => !orderByKeys.includes(filterKey));
3731
+ if (filtersKeysWithUnordered.length)
3732
+ filtersKeysWithUnordered.forEach((filterKey) => (fieldsToOrderBy = Object.assign(Object.assign({}, (![Where.EQUALS].includes(is(filters[filterKey]).operator)
3733
+ ? { [filterKey]: 'asc' }
3734
+ : {})), fieldsToOrderBy)));
3735
+ return Object.keys(fieldsToOrderBy).map((fieldName) => [
3736
+ fieldName,
3737
+ fieldsToOrderBy[fieldName],
3738
+ ]);
3739
+ };
3740
+ }
3741
+ generateCacheKey(findParams) {
3742
+ return FirestoreCacheKeyGeneratorHelper.generateFindCacheKey(this.model, findParams);
3743
+ }
3744
+ async find(find = {}, options) {
3745
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l;
3746
+ const logger = this.logger.with('find');
3747
+ 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) {
3748
+ const cacheKey = this.generateCacheKey(find);
3749
+ const cachedData = await this.cache.cacheAdapter.get(cacheKey);
3750
+ if (cachedData) {
3751
+ logger.log(`Dados recuperados do cache: ${cacheKey}`);
3752
+ return JSON.parse(cachedData);
3753
+ }
3754
+ }
3755
+ const collectionName = this.buildCollectionPathForFind(find.filters);
3756
+ const collection = this.collection(collectionName);
3757
+ 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;
3332
3758
  const req = { collection: collectionName, data: find };
3333
3759
  try {
3334
- 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 }));
3760
+ 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 }));
3335
3761
  const { fields, filters, limits, orderBy } = (intercepted === null || intercepted === void 0 ? void 0 : intercepted.find) || find;
3336
3762
  const queries = this.makeFirestoreWhere(filters || {});
3337
3763
  const ordination = this.makeFirestoreOrderBy(filters, orderBy);
@@ -3341,10 +3767,19 @@ const withFindFirestore = (MixinBase) => {
3341
3767
  .getDocs();
3342
3768
  const data = docs.docs.map((doc) => doc.data());
3343
3769
  const res = {
3344
- 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,
3770
+ 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,
3345
3771
  count: enableCount ? this.calculateCount(data, limits) : Infinity,
3346
3772
  };
3347
3773
  logger.log({ req, queries, ordination, offsets, res });
3774
+ 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) {
3775
+ const cacheKey = this.generateCacheKey(find);
3776
+ await this.cache.cacheAdapter.set({
3777
+ key: cacheKey,
3778
+ data: JSON.stringify(res),
3779
+ expirationInSeconds: ((_l = options === null || options === void 0 ? void 0 : options.cache) === null || _l === void 0 ? void 0 : _l.ttl) || this.cache.ttlDefault,
3780
+ });
3781
+ logger.log(`Dados salvos no cache: ${cacheKey}`);
3782
+ }
3348
3783
  return res;
3349
3784
  }
3350
3785
  catch (error) {
@@ -3448,24 +3883,41 @@ const withUpdateFirestore = (MixinBase) => {
3448
3883
  return options === null || options === void 0 ? void 0 : options.value;
3449
3884
  };
3450
3885
  return class UpdateFirestore extends MixinBase {
3886
+ getIdentifiersFromData(data) {
3887
+ const identifiers = {};
3888
+ const model = new this.model();
3889
+ const keyField = model.identifiersFields.shift();
3890
+ const identifierValue = getValueFromParams(data, keyField);
3891
+ identifiers[keyField] = identifierValue;
3892
+ return identifiers;
3893
+ }
3894
+ generateCacheKey(identifiers) {
3895
+ return FirestoreCacheKeyGeneratorHelper.generateGetCacheKey(this.model, identifiers);
3896
+ }
3451
3897
  async update(data) {
3452
- var _a, _b, _c, _d;
3898
+ var _a, _b, _c, _d, _e;
3453
3899
  const logger = this.logger.with('update');
3454
3900
  const collectionName = this.buildCollectionPathForUpdate(data);
3455
3901
  const model = new this.model();
3456
3902
  const keyField = model.identifiersFields.shift();
3457
3903
  const req = { collection: collectionName, data };
3904
+ if ((_a = this.cache) === null || _a === void 0 ? void 0 : _a.cacheAdapter) {
3905
+ const identifiers = this.getIdentifiersFromData(data);
3906
+ const cacheKey = this.generateCacheKey(identifiers);
3907
+ await this.cache.cacheAdapter.remove(cacheKey);
3908
+ logger.log(`Cache removido: ${cacheKey}`);
3909
+ }
3458
3910
  try {
3459
3911
  const identifiers = getValueFromParams(data, keyField);
3460
3912
  const docRef = this.collection(collectionName).getDoc(identifiers.toString());
3461
3913
  if (!(await docRef.get()).data())
3462
3914
  throw new NotFoundError(`Document '${collectionName}/${Object.values(identifiers.toString())}' not found`);
3463
3915
  const plainFromData = this.model.toInstance(this.paramsToPlain(data));
3464
- 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 }));
3916
+ 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 }));
3465
3917
  const builded = (intercepted === null || intercepted === void 0 ? void 0 : intercepted.instance) || plainFromData;
3466
3918
  await docRef.save(builded.toPlain());
3467
3919
  const docData = await docRef.get();
3468
- 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();
3920
+ 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();
3469
3921
  logger.log({ req, res, identifiers });
3470
3922
  return res;
3471
3923
  }
@@ -3491,17 +3943,25 @@ const withUpdateFirestore = (MixinBase) => {
3491
3943
 
3492
3944
  const withDeleteFirestore = (MixinBase) => {
3493
3945
  return class DeleteFirestore extends MixinBase {
3946
+ generateCacheKey(identifiers) {
3947
+ return FirestoreCacheKeyGeneratorHelper.generateGetCacheKey(this.model, identifiers);
3948
+ }
3494
3949
  async delete(identifiers) {
3495
- var _a, _b, _c, _d;
3950
+ var _a, _b, _c, _d, _e;
3496
3951
  const logger = this.logger.with('delete');
3497
3952
  const collectionName = this.buildCollectionPathForRemove(identifiers);
3498
3953
  const instance = this.model.toInstance(this.model.identifiersFields.reduce((acc, field) => (Object.assign(Object.assign({}, acc), { [field]: identifiers[field] })), {}));
3499
3954
  const req = { collection: collectionName, data: identifiers };
3955
+ if ((_a = this.cache) === null || _a === void 0 ? void 0 : _a.cacheAdapter) {
3956
+ const cacheKey = this.generateCacheKey(identifiers);
3957
+ await this.cache.cacheAdapter.remove(cacheKey);
3958
+ logger.log(`Cache removido: ${cacheKey}`);
3959
+ }
3500
3960
  try {
3501
- 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 }));
3961
+ 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 }));
3502
3962
  const builded = (intercepted === null || intercepted === void 0 ? void 0 : intercepted.instance) || instance;
3503
3963
  await this.collection(collectionName).getDoc(Object.values(builded.identifier).shift().toString()).delete();
3504
- await ((_d = (_c = this.interceptors) === null || _c === void 0 ? void 0 : _c.response) === null || _d === void 0 ? void 0 : _d.call(_c, instance, intercepted));
3964
+ await ((_e = (_d = this.interceptors) === null || _d === void 0 ? void 0 : _d.response) === null || _e === void 0 ? void 0 : _e.call(_d, instance, intercepted));
3505
3965
  logger.log({ req, res: undefined });
3506
3966
  }
3507
3967
  catch (error) {
@@ -3716,30 +4176,19 @@ class SubscriptionProductFirestoreRepository extends withCrudFirestore(withHelpe
3716
4176
  constructor({ firestore, interceptors }) {
3717
4177
  super({
3718
4178
  firestore,
3719
- collectionName: 'subscriptionProducts',
3720
- model: Product,
3721
- interceptors,
3722
- });
3723
- }
3724
- }
3725
-
3726
- class LogFirestoreRepository extends withCrudFirestore(withHelpers(withFirestore(Base))) {
3727
- constructor({ firestore, interceptors, }) {
3728
- super({
3729
- firestore,
3730
- collectionName: 'logs',
3731
- model: LogDocument,
4179
+ collectionName: 'subscriptionProducts',
4180
+ model: Product,
3732
4181
  interceptors,
3733
4182
  });
3734
4183
  }
3735
4184
  }
3736
4185
 
3737
- class ProductQueueFirestoreRepository extends withCrudFirestore(withHelpers(withFirestore(Base))) {
4186
+ class LogFirestoreRepository extends withCrudFirestore(withHelpers(withFirestore(Base))) {
3738
4187
  constructor({ firestore, interceptors, }) {
3739
4188
  super({
3740
4189
  firestore,
3741
- collectionName: 'queue_products_functions',
3742
- model: ProductQueue,
4190
+ collectionName: 'logs',
4191
+ model: LogDocument,
3743
4192
  interceptors,
3744
4193
  });
3745
4194
  }
@@ -3757,12 +4206,13 @@ class SequenceFirestoreRepository extends withCrudFirestore(withHelpers(withFire
3757
4206
  }
3758
4207
 
3759
4208
  class HomeFirestoreRepository extends withCrudFirestore(withHelpers(withFirestore(Base))) {
3760
- constructor({ firestore, interceptors }) {
4209
+ constructor({ firestore, interceptors, cache, }) {
3761
4210
  super({
3762
4211
  firestore,
3763
4212
  collectionName: 'dms',
3764
4213
  model: Home,
3765
4214
  interceptors,
4215
+ cache,
3766
4216
  });
3767
4217
  this.homeCategoryGroupToPlain = (homeCategoryGroup) => {
3768
4218
  var _a, _b, _c;
@@ -3819,89 +4269,97 @@ class HomeFirestoreRepository extends withCrudFirestore(withHelpers(withFirestor
3819
4269
  }
3820
4270
 
3821
4271
  class ShopMenuFirestoreRepository extends withCrudFirestore(withHelpers(withFirestore(Base))) {
3822
- constructor({ firestore, interceptors }) {
4272
+ constructor({ firestore, interceptors, cache, }) {
3823
4273
  super({
3824
4274
  firestore,
3825
4275
  collectionName: 'shopMenus',
3826
4276
  model: ShopMenu,
3827
4277
  interceptors,
4278
+ cache,
3828
4279
  });
3829
4280
  }
3830
4281
  }
3831
4282
 
3832
4283
  class ShopSettingsFirestoreRepository extends withCrudFirestore(withHelpers(withFirestore(Base))) {
3833
- constructor({ firestore, interceptors, }) {
4284
+ constructor({ firestore, interceptors, cache, }) {
3834
4285
  super({
3835
4286
  firestore,
3836
4287
  collectionName: 'shopSettings',
3837
4288
  model: ShopSettings,
3838
4289
  interceptors,
4290
+ cache,
3839
4291
  });
3840
4292
  }
3841
4293
  }
3842
4294
 
3843
4295
  class Buy2WinFirestoreRepository extends withCrudFirestore(withHelpers(withFirestore(Base))) {
3844
- constructor({ firestore, interceptors }) {
4296
+ constructor({ firestore, interceptors, cache, }) {
3845
4297
  super({
3846
4298
  firestore,
3847
4299
  collectionName: 'buy2win',
3848
4300
  model: Buy2Win,
3849
4301
  interceptors,
4302
+ cache,
3850
4303
  });
3851
4304
  }
3852
4305
  }
3853
4306
 
3854
4307
  class CampaignDashboardFirestoreRepository extends withCrudFirestore(withHelpers(withFirestore(Base))) {
3855
- constructor({ firestore, interceptors, }) {
4308
+ constructor({ firestore, interceptors, cache, }) {
3856
4309
  super({
3857
4310
  firestore,
3858
4311
  collectionName: 'dashboardCampaignsAuto',
3859
4312
  model: CampaignDashboard,
3860
4313
  interceptors,
4314
+ cache,
3861
4315
  });
3862
4316
  }
3863
4317
  }
3864
4318
 
3865
4319
  class CampaignHashtagFirestoreRepository extends withCrudFirestore(withHelpers(withFirestore(Base))) {
3866
- constructor({ firestore, interceptors, }) {
4320
+ constructor({ firestore, interceptors, cache, }) {
3867
4321
  super({
3868
4322
  firestore,
3869
4323
  collectionName: 'hashtagCampaignsAuto',
3870
4324
  model: CampaignHashtag,
3871
4325
  interceptors,
4326
+ cache,
3872
4327
  });
3873
4328
  }
3874
4329
  }
3875
4330
 
3876
4331
  class CheckoutFirestoreRepository extends withCrudFirestore(withHelpers(withFirestore(Base))) {
3877
- constructor({ firestore, interceptors }) {
4332
+ constructor({ firestore, interceptors, cache, }) {
3878
4333
  super({
3879
4334
  firestore,
3880
4335
  collectionName: 'checkouts',
3881
4336
  model: Checkout,
3882
4337
  interceptors,
4338
+ cache,
3883
4339
  });
3884
4340
  }
3885
4341
  }
3886
4342
 
3887
4343
  class CheckoutSubscriptionFirestoreRepository extends withCrudFirestore(withHelpers(withFirestore(Base))) {
3888
- constructor({ firestore, interceptors, }) {
4344
+ constructor({ firestore, interceptors, cache, }) {
3889
4345
  super({
3890
4346
  firestore,
3891
4347
  collectionName: 'checkoutsSubscription',
3892
4348
  model: CheckoutSubscription,
3893
4349
  interceptors,
4350
+ cache,
3894
4351
  });
3895
4352
  }
3896
4353
  }
3897
4354
 
3898
4355
  class CouponFirestoreRepository extends withCrudFirestore(withHelpers(withFirestore(Base))) {
3899
- constructor({ firestore, interceptors }) {
4356
+ constructor({ firestore, interceptors, cache, }) {
3900
4357
  super({
3901
4358
  firestore,
3902
4359
  collectionName: 'coupons',
3903
4360
  model: Coupon,
3904
4361
  interceptors,
4362
+ cache,
3905
4363
  });
3906
4364
  }
3907
4365
  buildModelInstance() {
@@ -3924,12 +4382,13 @@ class CouponFirestoreRepository extends withCrudFirestore(withHelpers(withFirest
3924
4382
  }
3925
4383
 
3926
4384
  class OrderFirestoreRepository extends withCrudFirestore(withHelpers(withFirestore(Base))) {
3927
- constructor({ firestore, interceptors }) {
4385
+ constructor({ firestore, interceptors, cache, }) {
3928
4386
  super({
3929
4387
  firestore,
3930
4388
  collectionName: 'orders',
3931
4389
  model: Order,
3932
4390
  interceptors,
4391
+ cache,
3933
4392
  fields: {
3934
4393
  status: FirestoreFieldType.String,
3935
4394
  },
@@ -3961,22 +4420,24 @@ class OrderFirestoreRepository extends withCrudFirestore(withHelpers(withFiresto
3961
4420
  }
3962
4421
 
3963
4422
  class LegacyOrderFirestoreRepository extends OrderFirestoreRepository {
3964
- constructor({ firestore, interceptors }) {
4423
+ constructor({ firestore, interceptors, cache, }) {
3965
4424
  super({
3966
4425
  firestore,
3967
4426
  interceptors,
4427
+ cache,
3968
4428
  });
3969
4429
  this.collectionName = 'legacyOrders';
3970
4430
  }
3971
4431
  }
3972
4432
 
3973
4433
  class OrderBlockedFirestoreRepository extends withCrudFirestore(withHelpers(withFirestore(Base))) {
3974
- constructor({ firestore, interceptors, }) {
4434
+ constructor({ firestore, interceptors, cache, }) {
3975
4435
  super({
3976
4436
  firestore,
3977
4437
  collectionName: 'paymentBlockedAttempts',
3978
4438
  model: OrderBlocked,
3979
4439
  interceptors,
4440
+ cache,
3980
4441
  });
3981
4442
  }
3982
4443
  async createBlockedOrderOrPayment(checkout, blockType, type, limiteRange, card = null) {
@@ -4008,130 +4469,141 @@ class OrderBlockedFirestoreRepository extends withCrudFirestore(withHelpers(with
4008
4469
  }
4009
4470
 
4010
4471
  class PaymentFirestoreRepository extends withCrudFirestore(withHelpers(withFirestore(Base))) {
4011
- constructor({ firestore, interceptors }) {
4472
+ constructor({ firestore, interceptors, cache, }) {
4012
4473
  super({
4013
4474
  firestore,
4014
4475
  collectionName: 'payments',
4015
4476
  model: Payment,
4016
4477
  interceptors,
4478
+ cache,
4017
4479
  });
4018
4480
  }
4019
4481
  }
4020
4482
 
4021
4483
  class SubscriptionPlanFirestoreRepository extends withCrudFirestore(withHelpers(withFirestore(Base))) {
4022
- constructor({ firestore, interceptors, }) {
4484
+ constructor({ firestore, interceptors, cache, }) {
4023
4485
  super({
4024
4486
  firestore,
4025
4487
  collectionName: 'subscriptionPlans',
4026
4488
  model: SubscriptionPlan,
4027
4489
  interceptors,
4490
+ cache,
4028
4491
  });
4029
4492
  }
4030
4493
  }
4031
4494
 
4032
4495
  class LeadFirestoreRepository extends withCrudFirestore(withHelpers(withFirestore(Base))) {
4033
- constructor({ firestore, interceptors }) {
4496
+ constructor({ firestore, interceptors, cache, }) {
4034
4497
  super({
4035
4498
  firestore,
4036
4499
  collectionName: 'leads',
4037
4500
  model: Lead,
4038
4501
  interceptors,
4502
+ cache,
4039
4503
  });
4040
4504
  }
4041
4505
  }
4042
4506
 
4043
4507
  class SubscriptionEditionFirestoreRepository extends withSubCollection(withCrudFirestore(withHelpers(withFirestore(Base)))) {
4044
- constructor({ firestore, interceptors }, parentRepository) {
4508
+ constructor({ firestore, interceptors, cache, }, parentRepository) {
4045
4509
  super({
4046
4510
  firestore,
4047
4511
  collectionName: 'editions',
4048
4512
  parentIdField: 'subscriptionId',
4049
4513
  model: Edition,
4050
4514
  interceptors,
4515
+ cache,
4051
4516
  });
4052
4517
  this.parentRepository = parentRepository;
4053
4518
  }
4054
4519
  }
4055
4520
 
4056
4521
  class SubscriptionFirestoreRepository extends withCrudFirestore(withHelpers(withFirestore(Base))) {
4057
- constructor({ firestore, interceptors, }) {
4522
+ constructor({ firestore, interceptors, cache, }) {
4058
4523
  super({
4059
4524
  firestore,
4060
4525
  collectionName: 'subscription',
4061
4526
  model: Subscription,
4062
4527
  interceptors,
4528
+ cache,
4063
4529
  });
4064
4530
  }
4065
4531
  }
4066
4532
 
4067
4533
  class SubscriptionMaterializationFirestoreRepository extends withCrudFirestore(withHelpers(withFirestore(Base))) {
4068
- constructor({ firestore, interceptors }) {
4534
+ constructor({ firestore, interceptors, cache, }) {
4069
4535
  super({
4070
4536
  firestore,
4071
4537
  collectionName: 'subscriptionMaterialization',
4072
4538
  model: SubscriptionMaterialization,
4073
4539
  interceptors,
4540
+ cache,
4074
4541
  });
4075
4542
  }
4076
4543
  }
4077
4544
 
4078
4545
  class SubscriptionPaymentFirestoreRepository extends withSubCollection(withCrudFirestore(withHelpers(withFirestore(Base)))) {
4079
- constructor({ firestore, interceptors }, parentRepository) {
4546
+ constructor({ firestore, interceptors, cache, }, parentRepository) {
4080
4547
  super({
4081
4548
  firestore,
4082
4549
  collectionName: 'payments',
4083
4550
  parentIdField: 'subscriptionId',
4084
4551
  model: SubscriptionPayment,
4085
4552
  interceptors,
4553
+ cache,
4086
4554
  });
4087
4555
  this.parentRepository = parentRepository;
4088
4556
  }
4089
4557
  }
4090
4558
 
4091
4559
  class SubscriptionSummaryFirestoreRepository extends withCrudFirestore(withHelpers(withFirestore(Base))) {
4092
- constructor({ firestore, interceptors, }) {
4560
+ constructor({ firestore, interceptors, cache, }) {
4093
4561
  super({
4094
4562
  firestore,
4095
4563
  collectionName: 'subscriptionSummary',
4096
4564
  model: SubscriptionSummary,
4097
4565
  interceptors,
4566
+ cache,
4098
4567
  });
4099
4568
  }
4100
4569
  }
4101
4570
 
4102
4571
  class UserAddressFirestoreRepository extends withSubCollection(withCrudFirestore(withHelpers(withFirestore(Base)))) {
4103
- constructor({ firestore, interceptors }, parentRepository) {
4572
+ constructor({ firestore, interceptors, cache, }, parentRepository) {
4104
4573
  super({
4105
4574
  firestore,
4106
4575
  collectionName: 'address',
4107
4576
  parentIdField: 'userId',
4108
4577
  model: UserAddress,
4109
4578
  interceptors,
4579
+ cache,
4110
4580
  });
4111
4581
  this.parentRepository = parentRepository;
4112
4582
  }
4113
4583
  }
4114
4584
 
4115
4585
  class UserBeautyProfileFirestoreRepository extends withSubCollection(withCrudFirestore(withHelpers(withFirestore(Base)))) {
4116
- constructor({ firestore, interceptors }, parentRepository) {
4586
+ constructor({ firestore, interceptors, cache, }, parentRepository) {
4117
4587
  super({
4118
4588
  firestore,
4119
4589
  collectionName: 'CX',
4120
4590
  parentIdField: 'userId',
4121
4591
  model: BeautyProfile,
4122
4592
  interceptors,
4593
+ cache,
4123
4594
  });
4124
4595
  this.parentRepository = parentRepository;
4125
4596
  }
4126
4597
  }
4127
4598
 
4128
4599
  class UserFirestoreRepository extends withCrudFirestore(withHelpers(withFirestore(Base))) {
4129
- constructor({ firestore, interceptors }) {
4600
+ constructor({ firestore, interceptors, cache, }) {
4130
4601
  super({
4131
4602
  firestore,
4132
4603
  collectionName: 'users',
4133
4604
  model: User,
4134
4605
  interceptors,
4606
+ cache,
4135
4607
  });
4136
4608
  }
4137
4609
  async get(identifiers) {
@@ -4191,13 +4663,14 @@ __decorate([
4191
4663
  ], UserFirestoreRepository.prototype, "checkIfExistsByField", null);
4192
4664
 
4193
4665
  class UserPaymentMethodFirestoreRepository extends withSubCollection(withCrudFirestore(withHelpers(withFirestore(Base)))) {
4194
- constructor({ firestore, interceptors }, parentRepository) {
4666
+ constructor({ firestore, interceptors, cache, }, parentRepository) {
4195
4667
  super({
4196
4668
  firestore,
4197
4669
  collectionName: 'payment_method',
4198
4670
  parentIdField: 'userId',
4199
4671
  model: UserPaymentMethod,
4200
4672
  interceptors,
4673
+ cache,
4201
4674
  });
4202
4675
  this.parentRepository = parentRepository;
4203
4676
  }
@@ -4309,331 +4782,52 @@ class ConnectCollectionService {
4309
4782
  return this;
4310
4783
  }
4311
4784
  fromStartAt(startingAt) {
4312
- this.startingAt = startingAt;
4313
- return this;
4314
- }
4315
- fromStartAfter(startingAt) {
4316
- this.startingAfter = startAfter(startingAt);
4317
- return this;
4318
- }
4319
- withConverter(params) {
4320
- this.converter = params;
4321
- this.reference = this.reference.withConverter({
4322
- toFirestore: (data) => params.toFirestore(data),
4323
- fromFirestore: (snapshot, options) => params.fromFirestore(new ConnectBaseDocumentSnapshot(snapshot), options),
4324
- });
4325
- return this;
4326
- }
4327
- async save(data, id) {
4328
- if (isEmpty(id))
4329
- return addDoc(this.reference, data);
4330
- const docRef = doc(this.reference, id);
4331
- await setDoc(docRef, data);
4332
- return docRef;
4333
- }
4334
- }
4335
-
4336
- class ConnectFirestoreService {
4337
- constructor(firestore) {
4338
- this.firestore = firestore;
4339
- }
4340
- getCollection(path) {
4341
- return new ConnectCollectionService(path, this.firestore);
4342
- }
4343
- getDocument(path) {
4344
- return new ConnectDocumentService(path, this.firestore);
4345
- }
4346
- }
4347
-
4348
- class FirebaseFileUploaderService {
4349
- constructor(storage, baseUrl) {
4350
- this.storage = storage;
4351
- this.baseUrl = baseUrl;
4352
- }
4353
- async upload(path, file) {
4354
- const storageRef = ref(this.storage, path);
4355
- return uploadBytes(storageRef, file).then((reference) => `${this.baseUrl}/${reference.ref.bucket}/${reference.ref.fullPath}`);
4356
- }
4357
- }
4358
-
4359
- class AttributeOptionHelper {
4360
- }
4361
- AttributeOptionHelper.FindByAttribute = (attributeName, fields) => {
4362
- var _a;
4363
- if (fields.includes(attributeName))
4364
- return { columnName: attributeName.toString(), attributeName, to: (value) => value, from: (value) => value };
4365
- const field = fields.find((columnOption) => isObject(columnOption) && Object.keys(columnOption).includes(attributeName.toString()));
4366
- const fieldOption = (_a = is(field)) === null || _a === void 0 ? void 0 : _a[attributeName];
4367
- if (isNil(fieldOption))
4368
- return { columnName: attributeName.toString(), attributeName };
4369
- if (Array.isArray(fieldOption))
4370
- return { columnName: attributeName.toString(), attributeName, fields: fieldOption };
4371
- return Object.assign({ attributeName, columnName: attributeName.toString() }, fieldOption);
4372
- };
4373
- AttributeOptionHelper.CheckIsColumnOption = (fieldValue) => !!(fieldValue === null || fieldValue === void 0 ? void 0 : fieldValue.columnName);
4374
- AttributeOptionHelper.FindColumnOptionFromList = (columnName, fields) => {
4375
- if (fields.includes(columnName))
4376
- return { columnName, attributeName: columnName };
4377
- const field = is(fields.find((field) => {
4378
- if (!isObject(field))
4379
- return false;
4380
- const columnOption = Object.values(field).find((option) => AttributeOptionHelper.CheckIsColumnOption(option) && option.columnName === columnName ? option : {});
4381
- return AttributeOptionHelper.CheckIsColumnOption(columnOption) && (columnOption === null || columnOption === void 0 ? void 0 : columnOption.columnName) === columnName;
4382
- }) || {});
4383
- const attributeName = Object.keys(field).find((fieldOptionFromList) => AttributeOptionHelper.CheckIsColumnOption(field[fieldOptionFromList]) || Array.isArray(field[fieldOptionFromList]));
4384
- const fieldOption = field === null || field === void 0 ? void 0 : field[attributeName];
4385
- if (Array.isArray(fieldOption))
4386
- return { attributeName: attributeName, fields: fieldOption };
4387
- return Object.assign({ attributeName: attributeName || columnName, columnName }, fieldOption);
4388
- };
4389
-
4390
- var HasuraGraphQLWhere;
4391
- (function (HasuraGraphQLWhere) {
4392
- HasuraGraphQLWhere["EQUALS"] = "_eq";
4393
- HasuraGraphQLWhere["GT"] = "_gt";
4394
- HasuraGraphQLWhere["GTE"] = "_gte";
4395
- HasuraGraphQLWhere["IN"] = "_in";
4396
- HasuraGraphQLWhere["NOTIN"] = "_nin";
4397
- HasuraGraphQLWhere["LT"] = "_lt";
4398
- HasuraGraphQLWhere["LTE"] = "_lte";
4399
- HasuraGraphQLWhere["LIKE"] = "_like";
4400
- HasuraGraphQLWhere["ILIKE"] = "_ilike";
4401
- HasuraGraphQLWhere["NOTLIKE"] = "_nlike";
4402
- HasuraGraphQLWhere["ISNULL"] = "_is_null";
4403
- HasuraGraphQLWhere["ISNOTNULL"] = "_is_null";
4404
- HasuraGraphQLWhere["JSON_CONTAINS"] = "_contains";
4405
- HasuraGraphQLWhere["JSON_HAS_KEYS_ANY"] = "_has_keys_any";
4406
- HasuraGraphQLWhere["IREGEX"] = "_iregex";
4407
- HasuraGraphQLWhere["REGEX"] = "_regex";
4408
- })(HasuraGraphQLWhere || (HasuraGraphQLWhere = {}));
4409
-
4410
- var HasuraGraphQLColumnType;
4411
- (function (HasuraGraphQLColumnType) {
4412
- HasuraGraphQLColumnType["Int"] = "Int";
4413
- HasuraGraphQLColumnType["Float"] = "Float";
4414
- HasuraGraphQLColumnType["Boolean"] = "Boolean";
4415
- HasuraGraphQLColumnType["String"] = "String";
4416
- HasuraGraphQLColumnType["DateTime"] = "timestampz";
4417
- HasuraGraphQLColumnType["Json"] = "json";
4418
- HasuraGraphQLColumnType["Jsonb"] = "jsonb";
4419
- HasuraGraphQLColumnType["Enum"] = "enum";
4420
- HasuraGraphQLColumnType["Uuid"] = "uuid";
4421
- })(HasuraGraphQLColumnType || (HasuraGraphQLColumnType = {}));
4422
-
4423
- class FilterOptionHelper {
4424
- }
4425
- FilterOptionHelper.CheckIfIsFilterOption = (filter) => !isNil(filter === null || filter === void 0 ? void 0 : filter.operator);
4426
- FilterOptionHelper.GetValueFromFilter = (filter, fieldOption) => {
4427
- if (!FilterOptionHelper.CheckIfIsFilterOption(filter))
4428
- return filter;
4429
- if (filter.operator === Where.ISNULL)
4430
- return true;
4431
- if (filter.operator === Where.ISNOTNULL)
4432
- return false;
4433
- const converter = fieldOption.to
4434
- ? fieldOption.to
4435
- : (value) => filter.operator === Where.LIKE && !Array.isArray(filter.value) && value.indexOf('%') < 0
4436
- ? `%${value}%`
4437
- : value;
4438
- const converterResult = Array.isArray(filter.value) && !fieldOption.fields && [Where.IN, Where.NOTIN].includes(filter.operator)
4439
- ? filter.value.map((fieldValue) => converter(fieldValue))
4440
- : converter(filter.value);
4441
- const newValue = filter.ignoreCase && !filter.ignoreAccent && !Array.isArray(filter.value) && converterResult.indexOf('%') < 0
4442
- ? `%${converterResult}%`
4443
- : converterResult;
4444
- return filter.ignoreAccent && !Array.isArray(filter.value)
4445
- ? FilterOptionHelper.buildInsensitiveSentence(newValue)
4446
- : newValue;
4447
- };
4448
- FilterOptionHelper.buildInsensitiveSentence = (value) => {
4449
- const valueWithoutAccents = FilterOptionHelper.removeAccents(value);
4450
- let result = '';
4451
- for (const char of valueWithoutAccents) {
4452
- const allCharOptions = [];
4453
- if (['a', 'e', 'i', 'o', 'u', 'c', 'A', 'E', 'I', 'O', 'U', 'C'].includes(char)) {
4454
- const charOptions = {
4455
- a: ['á', 'â', 'ã', 'à', 'a'],
4456
- e: ['é', 'ê', 'ẽ', 'è', 'e'],
4457
- i: ['í', 'î', 'ĩ', 'ì', 'i'],
4458
- o: ['ó', 'ô', 'õ', 'ò', 'o'],
4459
- u: ['ú', 'û', 'ũ', 'ù', 'u'],
4460
- c: ['ç', 'c'],
4461
- A: ['Á', 'Â', 'Ã', 'À', 'A'],
4462
- E: ['É', 'Ê', 'Ẽ', 'È', 'E'],
4463
- I: ['Í', 'Î', 'Ĩ', 'Ì', 'I'],
4464
- O: ['Ó', 'Ô', 'Õ', 'Ò', 'O'],
4465
- U: ['Ú', 'Û', 'Ũ', 'Ù', 'U'],
4466
- C: ['Ç', 'C'],
4467
- };
4468
- allCharOptions.push(...charOptions[char]);
4469
- result += `[${allCharOptions.join('')}]`;
4470
- }
4471
- else {
4472
- result += char;
4473
- }
4474
- }
4475
- return result;
4476
- };
4477
- FilterOptionHelper.removeAccents = (text) => {
4478
- return text.normalize('NFD').replace(/[\u0300-\u036f]/g, '');
4479
- };
4480
-
4481
- class BindFilterQueryHelper {
4482
- }
4483
- BindFilterQueryHelper.MakeGraphQLWhere = (filter, fields) => Object.keys(filter).reduce((variables, fieldName) => {
4484
- const columnOption = AttributeOptionHelper.FindByAttribute(fieldName, fields);
4485
- if (!columnOption.bindFindFilter)
4486
- return Object.assign(Object.assign({}, variables), {
4487
- [columnOption.columnName]: BindFilterQueryHelper.BuildWhereSentence(fieldName, filter[fieldName], fields),
4488
- });
4489
- const builtFilter = columnOption.bindFindFilter(filter[fieldName]);
4490
- return Object.assign(Object.assign({}, variables), Object.keys(builtFilter).reduce((variablesList, columnName) => (Object.assign(Object.assign({}, variablesList), { [columnName]: BindFilterQueryHelper.BuildWhereSentence(fieldName, builtFilter[columnName], fields) })), {}));
4491
- }, {});
4492
- BindFilterQueryHelper.BuildWhereSentence = (field, options, fields) => {
4493
- const fieldSentenceOptions = AttributeOptionHelper.FindByAttribute(field, fields);
4494
- const isNestedField = !Array.isArray(options) &&
4495
- isObject(options) &&
4496
- isNil(options === null || options === void 0 ? void 0 : options.operator) &&
4497
- isNil(options === null || options === void 0 ? void 0 : options.value) &&
4498
- isNil(fieldSentenceOptions === null || fieldSentenceOptions === void 0 ? void 0 : fieldSentenceOptions.to);
4499
- if (isNestedField)
4500
- return Object.keys(options).reduce((variables, key) => {
4501
- const fieldOptions = AttributeOptionHelper.FindByAttribute(key, (fieldSentenceOptions === null || fieldSentenceOptions === void 0 ? void 0 : fieldSentenceOptions.fields) || fields);
4502
- const columnName = fieldOptions.columnName;
4503
- const columnFields = fieldOptions.fields;
4504
- 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) });
4505
- }, {});
4506
- if (!Array.isArray(options) && !isNil(fieldSentenceOptions.fields))
4507
- return {
4508
- [fieldSentenceOptions.fields[0]]: BindFilterQueryHelper.BuildOperatorSentence(options, fieldSentenceOptions),
4509
- };
4510
- if (!Array.isArray(options) && isObject(options) && !FilterOptionHelper.CheckIfIsFilterOption(options))
4511
- options = Object.values(options)[0];
4512
- return Array.isArray(options)
4513
- ? options.reduce((whereSentence, option) => (Object.assign(Object.assign({}, whereSentence), BindFilterQueryHelper.BuildOperatorSentence(option, fieldSentenceOptions))), {})
4514
- : BindFilterQueryHelper.BuildOperatorSentence(options, fieldSentenceOptions);
4515
- };
4516
- BindFilterQueryHelper.BuildOperatorSentence = (options, fieldOption) => ({
4517
- [BindFilterQueryHelper.GetHasuraOperator(options, fieldOption)]: FilterOptionHelper.GetValueFromFilter(options, fieldOption),
4518
- });
4519
- BindFilterQueryHelper.GetHasuraOperator = (options, fieldOption) => FilterOptionHelper.CheckIfIsFilterOption(options)
4520
- ? fieldOption.type === HasuraGraphQLColumnType.Jsonb
4521
- ? BindFilterQueryHelper.GetHasuraJsonbOperator(options)
4522
- : options.operator === Where.LIKE && options.ignoreCase && options.ignoreAccent
4523
- ? HasuraGraphQLWhere.IREGEX
4524
- : options.operator === Where.LIKE && options.ignoreAccent
4525
- ? HasuraGraphQLWhere.REGEX
4526
- : options.operator === Where.LIKE && options.ignoreCase
4527
- ? HasuraGraphQLWhere.ILIKE
4528
- : HasuraGraphQLWhere[Object.keys(HasuraGraphQLWhere).find((graphQLOperator) => graphQLOperator ===
4529
- Object.keys(Where).find((operator) => Where[operator] === (options === null || options === void 0 ? void 0 : options.operator)))]
4530
- : HasuraGraphQLWhere.EQUALS;
4531
- BindFilterQueryHelper.GetHasuraJsonbOperator = (options) => options.operator === Where.IN
4532
- ? HasuraGraphQLWhere.JSON_CONTAINS
4533
- : options.operator === Where.LIKE
4534
- ? HasuraGraphQLWhere.JSON_HAS_KEYS_ANY
4535
- : HasuraGraphQLWhere[Object.keys(HasuraGraphQLWhere).find((graphQLOperator) => graphQLOperator ===
4536
- Object.keys(Where).find((operator) => Where[operator] === (options === null || options === void 0 ? void 0 : options.operator)))];
4785
+ this.startingAt = startingAt;
4786
+ return this;
4787
+ }
4788
+ fromStartAfter(startingAt) {
4789
+ this.startingAfter = startAfter(startingAt);
4790
+ return this;
4791
+ }
4792
+ withConverter(params) {
4793
+ this.converter = params;
4794
+ this.reference = this.reference.withConverter({
4795
+ toFirestore: (data) => params.toFirestore(data),
4796
+ fromFirestore: (snapshot, options) => params.fromFirestore(new ConnectBaseDocumentSnapshot(snapshot), options),
4797
+ });
4798
+ return this;
4799
+ }
4800
+ async save(data, id) {
4801
+ if (isEmpty(id))
4802
+ return addDoc(this.reference, data);
4803
+ const docRef = doc(this.reference, id);
4804
+ await setDoc(docRef, data);
4805
+ return docRef;
4806
+ }
4807
+ }
4537
4808
 
4538
- class GraphQLFieldHelper {
4539
- }
4540
- GraphQLFieldHelper.CheckIsGraphQLParams = (params) => !isString(params) && Array.isArray(params) && params.length >= 0 && !!params[0].operation;
4541
- GraphQLFieldHelper.ConvertModelFieldsToGraphQLFields = (fields) => {
4542
- return fields === null || fields === void 0 ? void 0 : fields.map((field) => {
4543
- if (isString(field))
4544
- return field.toString();
4545
- if (field === 'affected_rows')
4546
- return field;
4547
- const fieldName = Object.keys(field).shift();
4548
- const fieldValue = is(field[fieldName]);
4549
- if (Array.isArray(fieldValue))
4550
- return { [fieldName]: GraphQLFieldHelper.ConvertModelFieldsToGraphQLFields(fieldValue) };
4551
- if (!AttributeOptionHelper.CheckIsColumnOption(fieldValue))
4552
- return;
4553
- const isNestedField = !!fieldValue.fields;
4554
- if (isNestedField)
4555
- return GraphQLFieldHelper.ConvertNestedFieldsToGraphQLFields(fieldName, fieldValue);
4556
- return fieldValue.columnName;
4557
- }).filter((field) => !!field);
4558
- };
4559
- GraphQLFieldHelper.ConvertFieldValueFrom = (data, fields) => Object.keys(data).reduce((result, columnName) => {
4560
- const { attributeName, fields: attributeFields, from, } = AttributeOptionHelper.FindColumnOptionFromList(columnName, fields);
4561
- if (!!attributeFields && Array.isArray(attributeFields)) {
4562
- if (Array.isArray(data[columnName]))
4563
- return Object.assign(Object.assign({}, result), { [attributeName]: from
4564
- ? from(data[columnName], data)
4565
- : is(data[columnName]).map((value) => GraphQLFieldHelper.ConvertFieldValueFrom(is(value), attributeFields)) });
4566
- if (isObject(data[columnName]))
4567
- return Object.assign(Object.assign({}, result), { [attributeName]: !!from
4568
- ? from(data[columnName])
4569
- : GraphQLFieldHelper.ConvertFieldValueFrom(is(data[columnName]), attributeFields) });
4809
+ class ConnectFirestoreService {
4810
+ constructor(firestore) {
4811
+ this.firestore = firestore;
4570
4812
  }
4571
- if (!!from)
4572
- return Object.assign(Object.assign({}, result), { [attributeName]: from(data[columnName], data) });
4573
- return Object.assign(Object.assign({}, result), { [attributeName]: isString(data[columnName]) ? parseDateTime(data[columnName].toString()) : data[columnName] });
4574
- }, {});
4575
- GraphQLFieldHelper.ConvertFieldValueTo = (instance, fields, update = false) => {
4576
- var _a;
4577
- const data = ((_a = instance.toPlain) === null || _a === void 0 ? void 0 : _a.call(instance)) || instance;
4578
- return Object.keys(data).reduce((result, attributeName) => {
4579
- const { columnName, fields: attributeFields, foreignKeyColumn, to, bindPersistData, } = AttributeOptionHelper.FindByAttribute(attributeName, fields);
4580
- if (bindPersistData)
4581
- return Object.assign(Object.assign({}, result), bindPersistData(data[attributeName], instance));
4582
- if (isNil(columnName))
4583
- return result;
4584
- if (!!foreignKeyColumn &&
4585
- !isEmpty(foreignKeyColumn) &&
4586
- !Object.keys(foreignKeyColumn).filter((key) => { var _a; return !((_a = is(data[attributeName])) === null || _a === void 0 ? void 0 : _a[key]); }).length)
4587
- return Object.keys(foreignKeyColumn).reduce((object, current) => {
4588
- var _a;
4589
- const { columnName: foreignColumnName } = AttributeOptionHelper.FindByAttribute(foreignKeyColumn[current], fields);
4590
- return Object.assign(Object.assign({}, object), { [foreignColumnName]: (_a = data[attributeName]) === null || _a === void 0 ? void 0 : _a[current] });
4591
- }, Object.assign({}, result));
4592
- if (update &&
4593
- isObject(data[attributeName]) &&
4594
- !isNil(attributeFields) &&
4595
- !isDate(data[attributeName]))
4596
- return result;
4597
- if (!!columnName &&
4598
- Array.isArray(attributeFields) &&
4599
- isObject(data[attributeName])) {
4600
- const converted = !isNil(columnName) && to
4601
- ? to(instance[attributeName], instance)
4602
- : data[attributeName];
4603
- return Object.assign(Object.assign({}, result), (converted !== undefined
4604
- ? {
4605
- [columnName]: {
4606
- data: instance[attributeName] instanceof BaseModel
4607
- ? GraphQLFieldHelper.ConvertFieldValueTo(data[attributeName], attributeFields)
4608
- : converted,
4609
- },
4610
- }
4611
- : {}));
4612
- }
4613
- if (!!to)
4614
- return Object.assign(Object.assign({}, result), { [columnName]: to(instance[attributeName], instance) });
4615
- return Object.assign(Object.assign({}, result), { [columnName]: data[attributeName] });
4616
- }, {});
4617
- };
4618
- GraphQLFieldHelper.ConvertNestedFieldsToGraphQLFields = (fieldName, fieldValue) => {
4619
- const hasCustomFilters = !!fieldValue.filters;
4620
- if (hasCustomFilters)
4621
- return {
4622
- operation: fieldValue.columnName || fieldName,
4623
- fields: GraphQLFieldHelper.ConvertModelFieldsToGraphQLFields(fieldValue.fields),
4624
- variables: {
4625
- [`${fieldValue.columnName}_where`]: {
4626
- name: 'where',
4627
- type: fieldValue.filters.filterType,
4628
- value: BindFilterQueryHelper.MakeGraphQLWhere(fieldValue.filters.filters, fieldValue.fields),
4629
- required: true,
4630
- },
4631
- },
4632
- };
4633
- return {
4634
- [fieldValue.columnName || fieldName]: GraphQLFieldHelper.ConvertModelFieldsToGraphQLFields(fieldValue.fields),
4635
- };
4636
- };
4813
+ getCollection(path) {
4814
+ return new ConnectCollectionService(path, this.firestore);
4815
+ }
4816
+ getDocument(path) {
4817
+ return new ConnectDocumentService(path, this.firestore);
4818
+ }
4819
+ }
4820
+
4821
+ class FirebaseFileUploaderService {
4822
+ constructor(storage, baseUrl) {
4823
+ this.storage = storage;
4824
+ this.baseUrl = baseUrl;
4825
+ }
4826
+ async upload(path, file) {
4827
+ const storageRef = ref(this.storage, path);
4828
+ return uploadBytes(storageRef, file).then((reference) => `${this.baseUrl}/${reference.ref.bucket}/${reference.ref.fullPath}`);
4829
+ }
4830
+ }
4637
4831
 
4638
4832
  const withCreateHasuraGraphQL = (MixinBase) => {
4639
4833
  return class CreateHasuraGraphQLMixin extends MixinBase {
@@ -4682,7 +4876,13 @@ const withDeleteHasuraGraphQL = (MixinBase) => {
4682
4876
  this.deleteGraphQLOperation = (options === null || options === void 0 ? void 0 : options.deleteGraphQLOperation) || `delete_${this.tableName}_by_pk`;
4683
4877
  }
4684
4878
  async delete(identifiers) {
4879
+ var _a;
4685
4880
  this.logger = DebugHelper.from(this, 'delete');
4881
+ if ((_a = this.cache) === null || _a === void 0 ? void 0 : _a.cacheAdapter) {
4882
+ const cacheKey = CacheKeyGeneratorHelper.generateCacheKeyFromIdentifiers(this.model, identifiers);
4883
+ await this.cache.cacheAdapter.remove(cacheKey);
4884
+ this.logger.log(`Cache removido: ${cacheKey}`);
4885
+ }
4686
4886
  const instance = this.model.toInstance(identifiers);
4687
4887
  await this.mutation(this.deleteGraphQLOperation, this.model.identifiersFields.map((field) => AttributeOptionHelper.FindByAttribute(field, this.fields).columnName), this.model.identifiersFields.reduce((ids, identifier) => {
4688
4888
  const identifierBinded = identifier;
@@ -4720,6 +4920,7 @@ const withHasuraGraphQL = (MixinBase) => {
4720
4920
  this.model = options.model;
4721
4921
  this.fields = options.fields || this.model.identifiersFields;
4722
4922
  this.logger = DebugHelper.from(this);
4923
+ this.cache = options.cache;
4723
4924
  }
4724
4925
  async mutation(operation, fields, variables) {
4725
4926
  const resultQuery = mutation({
@@ -4821,9 +5022,29 @@ const withUpdateHasuraGraphQL = (MixinBase) => {
4821
5022
  this.updateGraphQLObjectType = (options === null || options === void 0 ? void 0 : options.updateGraphQLObjectType) || `${this.tableName}_set_input`;
4822
5023
  this.updateGraphQLPKType = (options === null || options === void 0 ? void 0 : options.updateGraphQLPKType) || `${this.tableName}_pk_columns_input`;
4823
5024
  }
5025
+ getIdentifiersFromData(data) {
5026
+ const instance = this.model.toInstance(data);
5027
+ const identifiers = {};
5028
+ this.model.identifiersFields.forEach((identifier) => {
5029
+ const field = identifier;
5030
+ if (!isNil(instance[field])) {
5031
+ identifiers[String(field)] = instance[field];
5032
+ }
5033
+ });
5034
+ return identifiers;
5035
+ }
4824
5036
  async update(data) {
5037
+ var _a;
4825
5038
  this.logger = DebugHelper.from(this, 'update');
4826
5039
  const plainData = this.paramsToPlain(data);
5040
+ if ((_a = this.cache) === null || _a === void 0 ? void 0 : _a.cacheAdapter) {
5041
+ const identifiers = this.getIdentifiersFromData(plainData);
5042
+ if (Object.keys(identifiers).length > 0) {
5043
+ const cacheKey = CacheKeyGeneratorHelper.generateCacheKeyFromIdentifiers(this.model, identifiers);
5044
+ await this.cache.cacheAdapter.remove(cacheKey);
5045
+ this.logger.log(`Cache removido: ${cacheKey}`);
5046
+ }
5047
+ }
4827
5048
  await this.mutation(this.updateGraphQLOperation, this.model.identifiersFields.map((field) => AttributeOptionHelper.FindByAttribute(field, this.fields).columnName), {
4828
5049
  _set: {
4829
5050
  type: this.updateGraphQLObjectType,
@@ -4864,8 +5085,20 @@ const withGetHasuraGraphQL = (MixinBase) => {
4864
5085
  super(...params);
4865
5086
  this.getGraphQLOperation = (options === null || options === void 0 ? void 0 : options.getGraphQLOperation) || `${this.tableName}_by_pk`;
4866
5087
  }
4867
- async get(identifiers) {
5088
+ generateCacheKey(identifiers) {
5089
+ return CacheKeyGeneratorHelper.generateCacheKeyFromIdentifiers(this.model, identifiers);
5090
+ }
5091
+ async get(identifiers, options) {
5092
+ var _a, _b, _c, _d, _e;
4868
5093
  this.logger = DebugHelper.from(this, 'get');
5094
+ 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)) {
5095
+ const cacheKey = this.generateCacheKey(identifiers);
5096
+ const cachedData = await this.cache.cacheAdapter.get(cacheKey);
5097
+ if (cachedData) {
5098
+ this.logger.log(`Dados recuperados do cache: ${cacheKey}`);
5099
+ return this.model.toInstance(JSON.parse(cachedData));
5100
+ }
5101
+ }
4869
5102
  const instance = this.model.toInstance(identifiers);
4870
5103
  const result = await this.query(this.getGraphQLOperation, this.fields, this.model.identifiersFields.reduce((ids, identifier) => {
4871
5104
  var _a;
@@ -4884,12 +5117,26 @@ const withGetHasuraGraphQL = (MixinBase) => {
4884
5117
  const data = result[this.getGraphQLOperation];
4885
5118
  if (isNil(data))
4886
5119
  throw new NotFoundError(`${instance.constructor.name} not found`);
4887
- return this.convertDataFromHasura(result[this.getGraphQLOperation]);
5120
+ const resultModel = this.convertDataFromHasura(result[this.getGraphQLOperation]);
5121
+ 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)) {
5122
+ const cacheKey = this.generateCacheKey(identifiers);
5123
+ await this.cache.cacheAdapter.set({
5124
+ key: cacheKey,
5125
+ data: JSON.stringify(resultModel.toPlain()),
5126
+ expirationInSeconds: ((_e = options === null || options === void 0 ? void 0 : options.cache) === null || _e === void 0 ? void 0 : _e.ttl) || this.cache.ttlDefault,
5127
+ });
5128
+ this.logger.log(`Dados salvos no cache: ${cacheKey}`);
5129
+ }
5130
+ return resultModel;
4888
5131
  }
4889
5132
  };
4890
5133
  };
4891
5134
 
4892
5135
  const withFindHasuraGraphQL = (MixinBase) => {
5136
+ const generateCacheKey = (model, params) => {
5137
+ const md5 = MD5GeneratorHelper.generateMD5(params);
5138
+ return `${model.name.toLowerCase()}:find:${md5}`;
5139
+ };
4893
5140
  return class FindHasuraGraphQLMixin extends MixinBase {
4894
5141
  constructor() {
4895
5142
  super(...arguments);
@@ -4928,12 +5175,20 @@ const withFindHasuraGraphQL = (MixinBase) => {
4928
5175
  return ((_a = AttributeOptionHelper.FindByAttribute(attr.toString().split('.').pop(), fields)) === null || _a === void 0 ? void 0 : _a.columnName) || attr;
4929
5176
  });
4930
5177
  }
4931
- async find(params) {
4932
- var _a, _b, _c, _d, _e, _f, _g;
5178
+ async find(params, options) {
5179
+ var _a, _b, _c, _d, _e, _f, _g, _h;
4933
5180
  this.logger = DebugHelper.from(this, 'find');
4934
- const { filters, limits, orderBy, options } = params || {};
5181
+ const { filters, limits, orderBy, options: findOptions } = params || {};
4935
5182
  const tableFiltersNamed = `${this.tableName}:${JSON.stringify(filters)}`;
4936
- const enableCount = (_a = options === null || options === void 0 ? void 0 : options.enableCount) !== null && _a !== void 0 ? _a : true;
5183
+ const enableCount = (_a = findOptions === null || findOptions === void 0 ? void 0 : findOptions.enableCount) !== null && _a !== void 0 ? _a : true;
5184
+ 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)) {
5185
+ const cacheKey = generateCacheKey(this.model, params);
5186
+ const cachedData = await this.cache.cacheAdapter.get(cacheKey);
5187
+ if (cachedData) {
5188
+ this.logger.log(`Dados recuperados do cache: ${cacheKey}`);
5189
+ return this.bindResult(JSON.parse(cachedData), { enableCount, findOptions, tableFiltersNamed });
5190
+ }
5191
+ }
4937
5192
  const variablesFilters = isNil(filters)
4938
5193
  ? {}
4939
5194
  : {
@@ -4984,7 +5239,7 @@ const withFindHasuraGraphQL = (MixinBase) => {
4984
5239
  ]
4985
5240
  : []),
4986
5241
  ...((!this.lastDistinct[tableFiltersNamed] &&
4987
- ((_c = (_b = params.options) === null || _b === void 0 ? void 0 : _b.distinct) === null || _c === void 0 ? void 0 : _c.map((distinct) => {
5242
+ ((_e = (_d = params.options) === null || _d === void 0 ? void 0 : _d.distinct) === null || _e === void 0 ? void 0 : _e.map((distinct) => {
4988
5243
  var _a, _b;
4989
5244
  const distinctOption = (_a = this.fields.find((fieldOption) => fieldOption === distinct)) !== null && _a !== void 0 ? _a : this.fields.find((fieldOption) => Object.keys(fieldOption).shift() === distinct);
4990
5245
  const fieldName = ((_b = Object.values(distinctOption).shift()) === null || _b === void 0 ? void 0 : _b.columnName) || distinct;
@@ -5004,29 +5259,43 @@ const withFindHasuraGraphQL = (MixinBase) => {
5004
5259
  }))) ||
5005
5260
  []),
5006
5261
  ]);
5262
+ 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)) {
5263
+ const cacheKey = generateCacheKey(this.model, params);
5264
+ await this.cache.cacheAdapter.set({
5265
+ key: cacheKey,
5266
+ data: JSON.stringify(result),
5267
+ expirationInSeconds: ((_h = options === null || options === void 0 ? void 0 : options.cache) === null || _h === void 0 ? void 0 : _h.ttl) || this.cache.ttlDefault,
5268
+ });
5269
+ this.logger.log(`Dados salvos no cache: ${cacheKey}`);
5270
+ }
5271
+ return this.bindResult(result, { enableCount, findOptions, tableFiltersNamed });
5272
+ }
5273
+ bindResult(result, { enableCount, findOptions, tableFiltersNamed, }) {
5274
+ var _a, _b, _c, _d;
5007
5275
  const data = result[this.tableName].map((row) => this.convertDataFromHasura(row));
5008
- 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)
5276
+ 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)
5009
5277
  ? {
5010
- minimal: options.minimal.reduce((minimals, current) => {
5278
+ minimal: findOptions.minimal.reduce((minimals, current) => {
5011
5279
  var _a;
5012
5280
  return (Object.assign(Object.assign({}, minimals), 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])));
5013
5281
  }, {}),
5014
5282
  }
5015
- : {})), (((_e = options === null || options === void 0 ? void 0 : options.maximum) === null || _e === void 0 ? void 0 : _e.length)
5283
+ : {})), (((_b = findOptions === null || findOptions === void 0 ? void 0 : findOptions.maximum) === null || _b === void 0 ? void 0 : _b.length)
5016
5284
  ? {
5017
- maximum: options.maximum.reduce((maximums, current) => {
5285
+ maximum: findOptions.maximum.reduce((maximums, current) => {
5018
5286
  var _a;
5019
5287
  return (Object.assign(Object.assign({}, maximums), 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])));
5020
5288
  }, {}),
5021
5289
  }
5022
- : {})), (((_f = options === null || options === void 0 ? void 0 : options.distinct) === null || _f === void 0 ? void 0 : _f.length) && {
5023
- 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) => {
5290
+ : {})), (((_c = findOptions === null || findOptions === void 0 ? void 0 : findOptions.distinct) === null || _c === void 0 ? void 0 : _c.length) && {
5291
+ 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) => {
5024
5292
  var _a, _b;
5025
5293
  const distinctOption = (_a = this.fields.find((fieldOption) => fieldOption === current)) !== null && _a !== void 0 ? _a : this.fields.find((fieldOption) => Object.keys(fieldOption).shift() === current);
5026
5294
  const fieldName = ((_b = Object.values(distinctOption).shift()) === null || _b === void 0 ? void 0 : _b.columnName) || current;
5027
5295
  return Object.assign(Object.assign({}, distinct), { [current.toString()]: result[`${this.tableName}_${current.toString()}_distinct`].map((obj) => obj[fieldName]) });
5028
5296
  }, {})),
5029
5297
  }));
5298
+ return findResult;
5030
5299
  }
5031
5300
  };
5032
5301
  };
@@ -5068,7 +5337,7 @@ __decorate([
5068
5337
  ], ProductErrorsHasuraGraphQL.prototype, "product", void 0);
5069
5338
 
5070
5339
  class CategoryCollectionChildrenHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGraphQL(Base)) {
5071
- constructor({ endpoint, authOptions, interceptors, }) {
5340
+ constructor({ endpoint, authOptions, interceptors, cache, }) {
5072
5341
  super({
5073
5342
  tableName: 'category_collection_children',
5074
5343
  model: CategoryCollectionChildren,
@@ -5099,12 +5368,13 @@ class CategoryCollectionChildrenHasuraGraphQLRepository extends withCrudHasuraGr
5099
5368
  },
5100
5369
  },
5101
5370
  ],
5371
+ cache,
5102
5372
  });
5103
5373
  }
5104
5374
  }
5105
5375
 
5106
5376
  class CategoryFilterHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGraphQL(Base)) {
5107
- constructor({ endpoint, authOptions, interceptors, }) {
5377
+ constructor({ endpoint, authOptions, interceptors, cache, }) {
5108
5378
  super({
5109
5379
  tableName: 'category_filter',
5110
5380
  model: CategoryFilter,
@@ -5186,6 +5456,7 @@ class CategoryFilterHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHa
5186
5456
  },
5187
5457
  },
5188
5458
  ],
5459
+ cache,
5189
5460
  });
5190
5461
  }
5191
5462
  deleteByCategory(categoryId) {
@@ -5221,13 +5492,14 @@ __decorate([
5221
5492
  ], CategoryFilterHasuraGraphQLRepository.prototype, "deleteByCategoryAndFilter", null);
5222
5493
 
5223
5494
  class CategoryHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGraphQL(Base)) {
5224
- constructor({ endpoint, authOptions, interceptors, }, productRepository, categoryFilterRepository) {
5495
+ constructor({ endpoint, authOptions, interceptors, cache, }, productRepository, categoryFilterRepository) {
5225
5496
  super({
5226
5497
  tableName: 'category',
5227
5498
  model: Category,
5228
5499
  endpoint,
5229
5500
  authOptions,
5230
5501
  interceptors,
5502
+ cache,
5231
5503
  fields: [
5232
5504
  { id: { columnName: 'id', to: (value) => +value, from: (value) => value.toString() } },
5233
5505
  { firestoreId: { columnName: 'firestore_id' } },
@@ -5324,6 +5596,17 @@ class CategoryHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGr
5324
5596
  });
5325
5597
  this.productRepository = productRepository;
5326
5598
  this.categoryFilterRepository = categoryFilterRepository;
5599
+ this.reorganizeMostRelevantsProducts = (products, mostRelevantsIds, limit) => {
5600
+ const mostRelevantWithouyStock = products.filter((product) => mostRelevantsIds.includes(product.id) && product.stock.quantity <= 0);
5601
+ const firstProducts = products
5602
+ .filter((product) => mostRelevantsIds.includes(product.id) && product.stock.quantity > 0)
5603
+ .sort((a, b) => mostRelevantsIds.indexOf(a.id) - mostRelevantsIds.indexOf(b.id));
5604
+ const lastProducts = products
5605
+ .filter((product) => !mostRelevantsIds.includes(product.id) && product.stock.quantity > 0)
5606
+ .concat(mostRelevantWithouyStock);
5607
+ const categoryMostRelevants = firstProducts.concat(lastProducts);
5608
+ return limit ? categoryMostRelevants.slice(0, limit) : categoryMostRelevants;
5609
+ };
5327
5610
  }
5328
5611
  async create(params) {
5329
5612
  const { images, mostRelevants, metadatas } = params, data = __rest(params, ["images", "mostRelevants", "metadatas"]);
@@ -5343,11 +5626,12 @@ class CategoryHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGr
5343
5626
  },
5344
5627
  } }));
5345
5628
  }
5346
- async get(identifiers) {
5629
+ async get(identifiers, optionsCache) {
5347
5630
  var _a;
5348
5631
  return Number.isNaN(+identifiers.id)
5349
- ? (_a = (await this.find({ filters: { firestoreId: identifiers.id }, options: { enableCount: false } })).data) === null || _a === void 0 ? void 0 : _a[0]
5350
- : super.get(identifiers);
5632
+ ? (_a = (await this.find({ filters: { firestoreId: identifiers.id }, options: { enableCount: false } }, optionsCache))
5633
+ .data) === null || _a === void 0 ? void 0 : _a[0]
5634
+ : super.get(identifiers, optionsCache);
5351
5635
  }
5352
5636
  async update(params) {
5353
5637
  const { products, id: checkId, metadatas, filters } = params, data = __rest(params, ["products", "id", "metadatas", "filters"]);
@@ -5359,7 +5643,7 @@ class CategoryHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGr
5359
5643
  category.filters = filters && (await this.updateFilters(+id, { filters }));
5360
5644
  return category;
5361
5645
  }
5362
- async getCategoryBySlug(slug, shop) {
5646
+ async getCategoryBySlug(slug, shop, optionsCache) {
5363
5647
  if (!slug)
5364
5648
  return null;
5365
5649
  const { data } = await this.find({
@@ -5371,14 +5655,14 @@ class CategoryHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGr
5371
5655
  options: {
5372
5656
  enableCount: false,
5373
5657
  },
5374
- });
5658
+ }, optionsCache);
5375
5659
  if (!data.length)
5376
5660
  throw new NotFoundError(`Category with slug ${slug} not found`);
5377
5661
  if (data.length > 1)
5378
5662
  throw new DuplicatedResultsError('Query returned duplicated values');
5379
5663
  return data.shift();
5380
5664
  }
5381
- async getCategoryByShop(shop) {
5665
+ async getCategoryByShop(shop, optionsCache) {
5382
5666
  if (!shop)
5383
5667
  return;
5384
5668
  const { data } = await this.find({
@@ -5390,10 +5674,10 @@ class CategoryHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGr
5390
5674
  options: {
5391
5675
  enableCount: false,
5392
5676
  },
5393
- });
5677
+ }, optionsCache);
5394
5678
  return data;
5395
5679
  }
5396
- async getCategoriesForHome(categoryIds, shop, limit = 4) {
5680
+ async getCategoriesForHome(categoryIds, shop, limit = 4, optionsCache) {
5397
5681
  if (!(categoryIds === null || categoryIds === void 0 ? void 0 : categoryIds.length))
5398
5682
  return [];
5399
5683
  const categoriesFirestore = categoryIds.filter((categoryId) => Number.isNaN(+categoryId));
@@ -5401,83 +5685,86 @@ class CategoryHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGr
5401
5685
  const categories = [];
5402
5686
  if (categoriesFirestore.length)
5403
5687
  categories.push(...(await this.find({
5404
- filters: { firestoreId: { operator: Where.IN, value: categoriesFirestore.filter(Boolean) }, published: true },
5405
- }).then(({ data }) => data)));
5688
+ filters: {
5689
+ firestoreId: { operator: Where.IN, value: categoriesFirestore.filter(Boolean) },
5690
+ published: true,
5691
+ },
5692
+ }, optionsCache).then(({ data }) => data)));
5406
5693
  if (categoriesHasura.length)
5407
5694
  categories.push(...(await this.find({
5408
5695
  filters: {
5409
5696
  id: { operator: Where.IN, value: categoriesHasura.filter(Boolean) },
5410
5697
  published: true,
5411
5698
  },
5412
- }).then(({ data }) => data)));
5699
+ }, optionsCache).then(({ data }) => data)));
5413
5700
  if (!categories.length)
5414
5701
  return [];
5415
5702
  const homeSections = await Promise.all(categories.map(async (category) => ({
5416
5703
  category,
5417
- products: await this.mountCategory(category, shop, { limit, hasStock: true }),
5704
+ products: await this.mountCategory(category, shop, { limit, hasStock: true }, optionsCache),
5418
5705
  })));
5419
5706
  return homeSections;
5420
5707
  }
5421
- async mountCategory(category, shop, options) {
5708
+ async mountCategory(category, shop, options, optionsCache) {
5422
5709
  var _a;
5423
5710
  if (!((_a = category === null || category === void 0 ? void 0 : category.products) === null || _a === void 0 ? void 0 : _a.length))
5424
5711
  return [];
5425
- const mostRelevants = category.getMostRelevantByShop(shop);
5426
- const mostRelevantProductsIds = [...new Set(mostRelevants.concat(category.products))];
5712
+ const fields = [
5713
+ 'id',
5714
+ 'name',
5715
+ 'slug',
5716
+ 'images',
5717
+ 'miniatures',
5718
+ 'price',
5719
+ 'fullPrice',
5720
+ 'subscriberDiscountPercentage',
5721
+ 'subscriberPrice',
5722
+ 'stock',
5723
+ 'published',
5724
+ 'CEST',
5725
+ 'EAN',
5726
+ 'NCM',
5727
+ 'brand',
5728
+ 'costPrice',
5729
+ 'hasVariants',
5730
+ 'isKit',
5731
+ 'sku',
5732
+ 'rate',
5733
+ 'tags',
5734
+ 'type',
5735
+ 'shoppingCount',
5736
+ 'gender',
5737
+ 'createdAt',
5738
+ ];
5427
5739
  const products = [];
5428
- const { data: productsData } = await this.productRepository.findCatalog({
5429
- filters: {
5430
- id: { operator: Where.IN, value: mostRelevantProductsIds },
5431
- published: true,
5432
- },
5433
- fields: [
5434
- 'id',
5435
- 'name',
5436
- 'slug',
5437
- 'images',
5438
- 'miniatures',
5439
- 'price',
5440
- 'fullPrice',
5441
- 'subscriberDiscountPercentage',
5442
- 'subscriberPrice',
5443
- 'stock',
5444
- 'published',
5445
- 'CEST',
5446
- 'EAN',
5447
- 'NCM',
5448
- 'brand',
5449
- 'costPrice',
5450
- 'hasVariants',
5451
- 'isKit',
5452
- 'sku',
5453
- 'rate',
5454
- 'tags',
5455
- 'type',
5456
- 'shoppingCount',
5457
- 'gender',
5458
- 'createdAt',
5459
- ],
5460
- options: { enableCount: false },
5461
- orderBy: {
5740
+ const mostRelevantsIds = category.getMostRelevantByShop(shop);
5741
+ if (mostRelevantsIds === null || mostRelevantsIds === void 0 ? void 0 : mostRelevantsIds.length) {
5742
+ const { data: mostRelevants } = await this.productRepository.findCatalog(Object.assign(Object.assign({ filters: Object.assign({ id: {
5743
+ operator: Where.IN,
5744
+ value: mostRelevantsIds,
5745
+ }, published: true }, (options.hasStock ? { stock: { quantity: { operator: Where.GT, value: 0 } } } : {})) }, (options.limit ? { limits: { limit: options.limit } } : {})), { fields, options: { enableCount: false }, orderBy: {
5746
+ stock: 'desc',
5747
+ shoppingCount: 'desc',
5748
+ rate: 'desc',
5749
+ name: 'asc',
5750
+ } }), shop === Shops.MENSMARKET ? 'male' : 'female', optionsCache);
5751
+ if (mostRelevants.length >= mostRelevantsIds.length)
5752
+ return this.reorganizeMostRelevantsProducts(mostRelevants, mostRelevantsIds, options.limit);
5753
+ products.push(...mostRelevants);
5754
+ }
5755
+ const productIds = category.products.filter((productId) => !mostRelevantsIds.includes(productId));
5756
+ const { data: productsData } = await this.productRepository.findCatalog(Object.assign(Object.assign({ filters: Object.assign({ id: {
5757
+ operator: Where.IN,
5758
+ value: productIds,
5759
+ }, published: true }, (options.hasStock ? { stock: { quantity: { operator: Where.GT, value: 0 } } } : {})) }, (options.limit ? { limits: { limit: options.limit } } : {})), { fields, options: { enableCount: false }, orderBy: {
5760
+ stock: 'desc',
5462
5761
  shoppingCount: 'desc',
5463
5762
  rate: 'desc',
5464
- stock: 'desc',
5465
5763
  name: 'asc',
5466
- },
5467
- }, shop === Shops.MENSMARKET ? 'male' : 'female');
5468
- const mostRelevantWithouyStock = productsData.filter((product) => mostRelevants.includes(product.id) && product.stock.quantity <= 0);
5469
- const firstProducts = productsData
5470
- .filter((product) => mostRelevants.includes(product.id) && product.stock.quantity > 0)
5471
- .sort((a, b) => mostRelevants.indexOf(a.id) - mostRelevants.indexOf(b.id));
5472
- const lastProducts = productsData
5473
- .filter((product) => !mostRelevants.includes(product.id) && product.stock.quantity > 0)
5474
- .concat(mostRelevantWithouyStock);
5475
- const categoryMostRelevants = firstProducts.concat(lastProducts);
5476
- const resultFinal = categoryMostRelevants.slice(0, options.limit);
5477
- products.push(...resultFinal);
5478
- return products;
5479
- }
5480
- async getChildren(parentId) {
5764
+ } }), shop === Shops.MENSMARKET ? 'male' : 'female', optionsCache);
5765
+ return this.reorganizeMostRelevantsProducts([...products, ...productsData], mostRelevantsIds, options.limit);
5766
+ }
5767
+ async getChildren(parentId, _optionsCache) {
5481
5768
  const { category_tree } = await this.query('category_tree', ['id', 'name', 'parent_id', 'slug', 'reference', 'published', 'shops'], {
5482
5769
  args: {
5483
5770
  type: 'category_tree_args',
@@ -5615,31 +5902,31 @@ class CategoryHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGr
5615
5902
  __decorate([
5616
5903
  Log(),
5617
5904
  __metadata("design:type", Function),
5618
- __metadata("design:paramtypes", [String, String]),
5905
+ __metadata("design:paramtypes", [String, String, Object]),
5619
5906
  __metadata("design:returntype", Promise)
5620
5907
  ], CategoryHasuraGraphQLRepository.prototype, "getCategoryBySlug", null);
5621
5908
  __decorate([
5622
5909
  Log(),
5623
5910
  __metadata("design:type", Function),
5624
- __metadata("design:paramtypes", [String]),
5911
+ __metadata("design:paramtypes", [String, Object]),
5625
5912
  __metadata("design:returntype", Promise)
5626
5913
  ], CategoryHasuraGraphQLRepository.prototype, "getCategoryByShop", null);
5627
5914
  __decorate([
5628
5915
  Log(),
5629
5916
  __metadata("design:type", Function),
5630
- __metadata("design:paramtypes", [Array, String, Object]),
5917
+ __metadata("design:paramtypes", [Array, String, Object, Object]),
5631
5918
  __metadata("design:returntype", Promise)
5632
5919
  ], CategoryHasuraGraphQLRepository.prototype, "getCategoriesForHome", null);
5633
5920
  __decorate([
5634
5921
  Log(),
5635
5922
  __metadata("design:type", Function),
5636
- __metadata("design:paramtypes", [Category, String, Object]),
5923
+ __metadata("design:paramtypes", [Category, String, Object, Object]),
5637
5924
  __metadata("design:returntype", Promise)
5638
5925
  ], CategoryHasuraGraphQLRepository.prototype, "mountCategory", null);
5639
5926
  __decorate([
5640
5927
  Log(),
5641
5928
  __metadata("design:type", Function),
5642
- __metadata("design:paramtypes", [Number]),
5929
+ __metadata("design:paramtypes", [Number, Object]),
5643
5930
  __metadata("design:returntype", Promise)
5644
5931
  ], CategoryHasuraGraphQLRepository.prototype, "getChildren", null);
5645
5932
  __decorate([
@@ -5650,7 +5937,7 @@ __decorate([
5650
5937
  ], CategoryHasuraGraphQLRepository.prototype, "isChild", null);
5651
5938
 
5652
5939
  class CategoryProductHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGraphQL(Base)) {
5653
- constructor({ endpoint, authOptions, interceptors, }) {
5940
+ constructor({ endpoint, authOptions, interceptors, cache, }) {
5654
5941
  super({
5655
5942
  tableName: 'category_product',
5656
5943
  model: CategoryProduct,
@@ -5658,6 +5945,7 @@ class CategoryProductHasuraGraphQLRepository extends withCrudHasuraGraphQL(withH
5658
5945
  authOptions,
5659
5946
  interceptors,
5660
5947
  fields: [{ productId: { columnName: 'product_id' } }, { categoryId: { columnName: 'category_id' } }, 'order'],
5948
+ cache,
5661
5949
  });
5662
5950
  }
5663
5951
  async removeProductFromCategory(categoryId, productId) {
@@ -5684,7 +5972,7 @@ class CategoryProductHasuraGraphQLRepository extends withCrudHasuraGraphQL(withH
5684
5972
  }
5685
5973
 
5686
5974
  class FilterHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGraphQL(Base)) {
5687
- constructor({ endpoint, authOptions, interceptors, }, filterOptionRepository, categoryFilterRepository) {
5975
+ constructor({ endpoint, authOptions, interceptors, cache, }, filterOptionRepository, categoryFilterRepository) {
5688
5976
  super({
5689
5977
  tableName: 'filter',
5690
5978
  model: Filter,
@@ -5724,6 +6012,7 @@ class FilterHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGrap
5724
6012
  },
5725
6013
  },
5726
6014
  ],
6015
+ cache,
5727
6016
  });
5728
6017
  this.filterOptionRepository = filterOptionRepository;
5729
6018
  this.categoryFilterRepository = categoryFilterRepository;
@@ -5810,7 +6099,7 @@ __decorate([
5810
6099
  ], FilterHasuraGraphQLRepository.prototype, "deleteOptions", null);
5811
6100
 
5812
6101
  class FilterOptionHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGraphQL(Base)) {
5813
- constructor({ endpoint, authOptions, interceptors, }) {
6102
+ constructor({ endpoint, authOptions, interceptors, cache, }) {
5814
6103
  super({
5815
6104
  tableName: 'filter_option',
5816
6105
  model: FilterOption,
@@ -5824,18 +6113,20 @@ class FilterOptionHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasu
5824
6113
  { createdAt: { columnName: 'created_at' } },
5825
6114
  { updatedAt: { columnName: 'updated_at' } },
5826
6115
  ],
6116
+ cache,
5827
6117
  });
5828
6118
  }
5829
6119
  }
5830
6120
 
5831
6121
  class ProductErrorsHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGraphQL(Base)) {
5832
- constructor({ endpoint, authOptions, interceptors, }, productRepository) {
6122
+ constructor({ endpoint, authOptions, interceptors, cache, }, productRepository) {
5833
6123
  super({
5834
6124
  tableName: 'product_errors',
5835
6125
  model: ProductErrorsHasuraGraphQL,
5836
6126
  endpoint,
5837
6127
  authOptions,
5838
6128
  interceptors,
6129
+ cache,
5839
6130
  fields: [
5840
6131
  {
5841
6132
  productId: {
@@ -5922,7 +6213,7 @@ class ProductHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGra
5922
6213
  { updatedAt: { columnName: 'updated_at' } },
5923
6214
  ];
5924
6215
  }
5925
- constructor({ endpoint, authOptions, interceptors, }) {
6216
+ constructor({ endpoint, authOptions, interceptors, cache, }) {
5926
6217
  super({
5927
6218
  tableName: 'product',
5928
6219
  model: ProductHasuraGraphQL,
@@ -5930,6 +6221,7 @@ class ProductHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGra
5930
6221
  authOptions,
5931
6222
  interceptors,
5932
6223
  fields: [],
6224
+ cache,
5933
6225
  });
5934
6226
  this.bindReviewToModel = (plain) => ProductReview.toInstance(Object.assign(Object.assign({}, is(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 }));
5935
6227
  this.bindReviewToHasura = (review) => (Object.assign(Object.assign({}, is(omit(review, ['productId', 'createdAt', 'updatedAt', 'personId', 'orderId']))), { person_id: review.personId, order_id: review.orderId }));
@@ -6114,17 +6406,18 @@ class ProductHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGra
6114
6406
  }
6115
6407
  return product;
6116
6408
  }
6117
- async get(identifiers) {
6409
+ async get(identifiers, options) {
6118
6410
  var _a;
6119
6411
  const product = Number.isNaN(+identifiers.id)
6120
- ? (_a = (await this.find({ filters: { firestoreId: identifiers.id }, options: { enableCount: false } })).data) === null || _a === void 0 ? void 0 : _a[0]
6121
- : await super.get(identifiers);
6412
+ ? (_a = (await this.find({ filters: { firestoreId: identifiers.id }, options: { enableCount: false } }, options))
6413
+ .data) === null || _a === void 0 ? void 0 : _a[0]
6414
+ : await super.get(identifiers, options);
6122
6415
  if (product.productId)
6123
6416
  throw new NotFoundError('Product not found, it is a variant');
6124
- product.reviews = product.reviews || (await this.findReviewsByProduct(+product.id));
6417
+ product.reviews = product.reviews || (await this.findReviewsByProduct(+product.id, options));
6125
6418
  return product;
6126
6419
  }
6127
- async find(params) {
6420
+ async find(params, optionsParams) {
6128
6421
  var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m;
6129
6422
  const _o = params || {}, { filters, fields } = _o, options = __rest(_o, ["filters", "fields"]);
6130
6423
  const bindFields = fields ||
@@ -6146,10 +6439,18 @@ class ProductHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGra
6146
6439
  'fullPrice',
6147
6440
  ]
6148
6441
  : []),
6149
- ] }));
6442
+ ] }), optionsParams);
6150
6443
  }
6151
- async getBySlug(slug) {
6152
- var _a;
6444
+ async getBySlug(slug, options) {
6445
+ var _a, _b, _c, _d, _e, _f;
6446
+ 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)) {
6447
+ const cacheKey = `${this.model.name.toLowerCase()}:slug:${slug}`;
6448
+ const cachedData = await this.cache.cacheAdapter.get(cacheKey);
6449
+ if (cachedData) {
6450
+ this.logger.log(`Dados recuperados do cache: ${cacheKey}`);
6451
+ return this.model.toInstance(JSON.parse(cachedData));
6452
+ }
6453
+ }
6153
6454
  const result = await this.find({
6154
6455
  filters: {
6155
6456
  slug,
@@ -6161,8 +6462,17 @@ class ProductHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGra
6161
6462
  });
6162
6463
  if (!result.data.length)
6163
6464
  return null;
6164
- const product = (_a = result === null || result === void 0 ? void 0 : result.data) === null || _a === void 0 ? void 0 : _a.shift();
6465
+ const product = (_c = result === null || result === void 0 ? void 0 : result.data) === null || _c === void 0 ? void 0 : _c.shift();
6165
6466
  RoundProductPricesHelper.roundProductPrices(product);
6467
+ 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) {
6468
+ const cacheKey = `${this.model.name.toLowerCase()}:slug:${slug}`;
6469
+ await this.cache.cacheAdapter.set({
6470
+ key: cacheKey,
6471
+ data: JSON.stringify(product.toPlain()),
6472
+ expirationInSeconds: ((_f = options === null || options === void 0 ? void 0 : options.cache) === null || _f === void 0 ? void 0 : _f.ttl) || this.cache.ttlDefault,
6473
+ });
6474
+ this.logger.log(`Dados salvos no cache: ${cacheKey}`);
6475
+ }
6166
6476
  return product;
6167
6477
  }
6168
6478
  async update(params) {
@@ -6175,13 +6485,22 @@ class ProductHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGra
6175
6485
  product.metadata = metadata && (await this.updateMetadata(+id, { metadata }));
6176
6486
  return product;
6177
6487
  }
6178
- async fetchProductReviews() {
6488
+ async fetchProductReviews(filters, options) {
6489
+ var _a, _b, _c, _d, _e;
6490
+ 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)) {
6491
+ const cacheKey = `${this.model.name.toLowerCase()}:all-reviews:${MD5GeneratorHelper.generateMD5(filters)}`;
6492
+ const cachedData = await this.cache.cacheAdapter.get(cacheKey);
6493
+ if (cachedData) {
6494
+ this.logger.log(`Dados recuperados do cache: ${cacheKey}`);
6495
+ return JSON.parse(cachedData);
6496
+ }
6497
+ }
6179
6498
  let data = [];
6180
6499
  let count = 0;
6181
6500
  let offset = 0;
6182
- const limit = 500;
6501
+ const limit = (filters === null || filters === void 0 ? void 0 : filters.limit) || 500;
6183
6502
  do {
6184
- const result = await super.find(Object.assign({ fields: ['id', 'name', 'sku', 'reviews'] }, ({
6503
+ const result = await super.find(Object.assign({ fields: ['id', 'name', 'sku', 'reviews'] }, (limit && {
6185
6504
  limits: {
6186
6505
  offset,
6187
6506
  limit,
@@ -6191,12 +6510,50 @@ class ProductHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGra
6191
6510
  count = result.data.length;
6192
6511
  offset += limit;
6193
6512
  } while (count === limit);
6194
- return data.reduce((reviews, product) => [
6513
+ const reviews = data.reduce((reviews, product) => [
6195
6514
  ...reviews,
6196
6515
  ...product.reviews.map((review) => (Object.assign(Object.assign({}, review), { reviewStatus: this.getReviewStatus(review), productId: product.id, productName: product.name, productSku: product.sku }))),
6197
6516
  ], []);
6198
- }
6199
- async fetchReviews(status) {
6517
+ let filteredReviews = reviews;
6518
+ if (filters.sku) {
6519
+ filteredReviews = filteredReviews.filter((review) => review.productSku === filters.sku);
6520
+ }
6521
+ if (filters.status) {
6522
+ filteredReviews = filteredReviews.filter((review) => review.reviewStatus === filters.status);
6523
+ }
6524
+ if (filters.email) {
6525
+ filteredReviews = filteredReviews.filter((review) => review.email === filters.email);
6526
+ }
6527
+ if (filters.rate) {
6528
+ filteredReviews = filteredReviews.filter((review) => review.rate === filters.rate);
6529
+ }
6530
+ if (filters.period) {
6531
+ filteredReviews = filteredReviews.filter((review) => {
6532
+ const reviewDate = new Date(review.createdAt);
6533
+ return reviewDate >= filters.period.start && reviewDate <= filters.period.end;
6534
+ });
6535
+ }
6536
+ 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)) {
6537
+ const cacheKey = `${this.model.name.toLowerCase()}:all-reviews:${MD5GeneratorHelper.generateMD5(filters)}`;
6538
+ await this.cache.cacheAdapter.set({
6539
+ key: cacheKey,
6540
+ data: JSON.stringify(filteredReviews),
6541
+ expirationInSeconds: ((_e = options === null || options === void 0 ? void 0 : options.cache) === null || _e === void 0 ? void 0 : _e.ttl) || this.cache.ttlDefault,
6542
+ });
6543
+ this.logger.log(`Dados salvos no cache: ${cacheKey}`);
6544
+ }
6545
+ return filteredReviews;
6546
+ }
6547
+ async fetchReviews(status, options) {
6548
+ var _a, _b, _c, _d, _e;
6549
+ 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)) {
6550
+ const cacheKey = `${this.model.name.toLowerCase()}:reviews:${status}`;
6551
+ const cachedData = await this.cache.cacheAdapter.get(cacheKey);
6552
+ if (cachedData) {
6553
+ this.logger.log(`Dados recuperados do cache: ${cacheKey}`);
6554
+ return JSON.parse(cachedData);
6555
+ }
6556
+ }
6200
6557
  const reviewsExpression = {
6201
6558
  status: status === 'pending'
6202
6559
  ? { [HasuraGraphQLWhere.ISNULL]: true }
@@ -6205,7 +6562,7 @@ class ProductHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGra
6205
6562
  const { product: data } = await this.query('product', ['id', 'name', 'sku', { reviews: { columnName: 'reviews', fields: this.reviewsFields } }], {
6206
6563
  where: { value: { reviews: reviewsExpression }, type: 'product_bool_exp', required: true },
6207
6564
  });
6208
- return data.reduce((reviews, product) => [
6565
+ const reviews = data.reduce((reviews, product) => [
6209
6566
  ...reviews,
6210
6567
  ...product.reviews
6211
6568
  .filter((review) => (status === 'pending' && [undefined, null].includes(review.status)) ||
@@ -6213,9 +6570,20 @@ class ProductHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGra
6213
6570
  (status === 'rejected' && review.status === false))
6214
6571
  .map((review) => (Object.assign(Object.assign({}, this.bindReviewToModel(review)), { productId: product.id, productName: product.name, productSku: product.sku }))),
6215
6572
  ], []);
6573
+ 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)) {
6574
+ const cacheKey = `${this.model.name.toLowerCase()}:reviews:${status}`;
6575
+ await this.cache.cacheAdapter.set({
6576
+ key: cacheKey,
6577
+ data: JSON.stringify(reviews),
6578
+ expirationInSeconds: ((_e = options === null || options === void 0 ? void 0 : options.cache) === null || _e === void 0 ? void 0 : _e.ttl) || this.cache.ttlDefault,
6579
+ });
6580
+ this.logger.log(`Dados salvos no cache: ${cacheKey}`);
6581
+ }
6582
+ return reviews;
6216
6583
  }
6217
- async findCatalog(params, mainGender) {
6218
- 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' })), omit(params.orderBy, ['hasStock', 'intGender'])) }));
6584
+ async findCatalog(params, mainGender, options) {
6585
+ 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' })), omit(params.orderBy, ['hasStock', 'intGender'])) }), options);
6586
+ return result;
6219
6587
  }
6220
6588
  async cleanShoppingCountFromIds(ids) {
6221
6589
  return await this.mutation('update_product', ['affected_rows'], {
@@ -6322,7 +6690,16 @@ class ProductHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGra
6322
6690
  return (_b = data === null || data === void 0 ? void 0 : data[0]) === null || _b === void 0 ? void 0 : _b.id;
6323
6691
  throw new NotFoundError(`Product with id ${id} not found`);
6324
6692
  }
6325
- async findReviewsByProduct(productId) {
6693
+ async findReviewsByProduct(productId, options) {
6694
+ var _a, _b, _c, _d, _e;
6695
+ 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)) {
6696
+ const cacheKey = `${this.model.name.toLowerCase()}:reviews:product:${productId}`;
6697
+ const cachedData = await this.cache.cacheAdapter.get(cacheKey);
6698
+ if (cachedData) {
6699
+ this.logger.log(`Dados recuperados do cache: ${cacheKey}`);
6700
+ return JSON.parse(cachedData);
6701
+ }
6702
+ }
6326
6703
  const { product_review: data } = await this.query('product_review', this.reviewsFields, {
6327
6704
  where: {
6328
6705
  value: {
@@ -6332,7 +6709,17 @@ class ProductHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGra
6332
6709
  required: true,
6333
6710
  },
6334
6711
  });
6335
- return data && data.map((review) => this.bindReviewToModel(review));
6712
+ const reviews = data && data.map((review) => this.bindReviewToModel(review));
6713
+ 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) {
6714
+ const cacheKey = `${this.model.name.toLowerCase()}:reviews:product:${productId}`;
6715
+ await this.cache.cacheAdapter.set({
6716
+ key: cacheKey,
6717
+ data: JSON.stringify(reviews),
6718
+ expirationInSeconds: ((_e = options === null || options === void 0 ? void 0 : options.cache) === null || _e === void 0 ? void 0 : _e.ttl) || this.cache.ttlDefault,
6719
+ });
6720
+ this.logger.log(`Dados salvos no cache: ${cacheKey}`);
6721
+ }
6722
+ return reviews;
6336
6723
  }
6337
6724
  async findReview(review, productId) {
6338
6725
  if (review.id)
@@ -6418,25 +6805,25 @@ class ProductHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGra
6418
6805
  __decorate([
6419
6806
  Log(),
6420
6807
  __metadata("design:type", Function),
6421
- __metadata("design:paramtypes", [String]),
6808
+ __metadata("design:paramtypes", [String, Object]),
6422
6809
  __metadata("design:returntype", Promise)
6423
6810
  ], ProductHasuraGraphQLRepository.prototype, "getBySlug", null);
6424
6811
  __decorate([
6425
6812
  Log(),
6426
6813
  __metadata("design:type", Function),
6427
- __metadata("design:paramtypes", []),
6814
+ __metadata("design:paramtypes", [Object, Object]),
6428
6815
  __metadata("design:returntype", Promise)
6429
6816
  ], ProductHasuraGraphQLRepository.prototype, "fetchProductReviews", null);
6430
6817
  __decorate([
6431
6818
  Log(),
6432
6819
  __metadata("design:type", Function),
6433
- __metadata("design:paramtypes", [String]),
6820
+ __metadata("design:paramtypes", [String, Object]),
6434
6821
  __metadata("design:returntype", Promise)
6435
6822
  ], ProductHasuraGraphQLRepository.prototype, "fetchReviews", null);
6436
6823
  __decorate([
6437
6824
  Log(),
6438
6825
  __metadata("design:type", Function),
6439
- __metadata("design:paramtypes", [Object, Object]),
6826
+ __metadata("design:paramtypes", [Object, Object, Object]),
6440
6827
  __metadata("design:returntype", Promise)
6441
6828
  ], ProductHasuraGraphQLRepository.prototype, "findCatalog", null);
6442
6829
  __decorate([
@@ -6444,10 +6831,16 @@ __decorate([
6444
6831
  __metadata("design:type", Function),
6445
6832
  __metadata("design:paramtypes", [Array]),
6446
6833
  __metadata("design:returntype", Promise)
6447
- ], ProductHasuraGraphQLRepository.prototype, "cleanShoppingCountFromIds", null);
6834
+ ], ProductHasuraGraphQLRepository.prototype, "cleanShoppingCountFromIds", null);
6835
+ __decorate([
6836
+ Log(),
6837
+ __metadata("design:type", Function),
6838
+ __metadata("design:paramtypes", [Number, Object]),
6839
+ __metadata("design:returntype", Promise)
6840
+ ], ProductHasuraGraphQLRepository.prototype, "findReviewsByProduct", null);
6448
6841
 
6449
6842
  class ProductReviewHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGraphQL(Base)) {
6450
- constructor({ endpoint, authOptions, interceptors, }) {
6843
+ constructor({ endpoint, authOptions, interceptors, cache, }) {
6451
6844
  super({
6452
6845
  tableName: 'product_review',
6453
6846
  model: ProductReview,
@@ -6471,6 +6864,7 @@ class ProductReviewHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHas
6471
6864
  { createdAt: { columnName: 'created_at' } },
6472
6865
  { updatedAt: { columnName: 'updated_at' } },
6473
6866
  ],
6867
+ cache,
6474
6868
  });
6475
6869
  }
6476
6870
  async updateManyStatus(reviews) {
@@ -6512,13 +6906,14 @@ __decorate([
6512
6906
  ], ProductReviewHasuraGraphQLRepository.prototype, "disaproveReview", null);
6513
6907
 
6514
6908
  class ProductStockNotificationHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGraphQL(Base)) {
6515
- constructor({ endpoint, authOptions, interceptors, }) {
6909
+ constructor({ endpoint, authOptions, interceptors, cache, }) {
6516
6910
  super({
6517
6911
  tableName: 'product_stock_notification',
6518
6912
  model: ProductStockNotification,
6519
6913
  endpoint,
6520
6914
  authOptions,
6521
6915
  interceptors,
6916
+ cache,
6522
6917
  fields: [
6523
6918
  'id',
6524
6919
  { productId: { columnName: 'product_id' } },
@@ -6573,13 +6968,14 @@ class ProductStockNotificationHasuraGraphQLRepository extends withCrudHasuraGrap
6573
6968
  }
6574
6969
 
6575
6970
  class VariantHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGraphQL(Base)) {
6576
- constructor({ endpoint, authOptions, interceptors, }) {
6971
+ constructor({ endpoint, authOptions, interceptors, cache, }) {
6577
6972
  super({
6578
6973
  tableName: 'product',
6579
6974
  model: VariantHasuraGraphQL,
6580
6975
  endpoint,
6581
6976
  authOptions,
6582
6977
  interceptors,
6978
+ cache,
6583
6979
  fields: [
6584
6980
  { id: { columnName: 'id', to: (value) => +value, from: (value) => value.toString() } },
6585
6981
  { firestoreId: { columnName: 'firestore_id' } },
@@ -6686,13 +7082,14 @@ class WishlistHasuraGraphQL extends Wishlist {
6686
7082
  }
6687
7083
 
6688
7084
  class WishlistHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGraphQL(Base)) {
6689
- constructor({ endpoint, authOptions, interceptors, }, categoryProductRepository) {
7085
+ constructor({ endpoint, authOptions, interceptors, cache, }, categoryProductRepository) {
6690
7086
  super({
6691
7087
  tableName: 'category',
6692
7088
  model: WishlistHasuraGraphQL,
6693
7089
  endpoint,
6694
7090
  authOptions,
6695
7091
  interceptors,
7092
+ cache,
6696
7093
  fields: [
6697
7094
  { id: { columnName: 'id', to: (value) => +value, from: (value) => value.toString() } },
6698
7095
  { firestoreId: { columnName: 'firestore_id' } },
@@ -7433,4 +7830,4 @@ class ProductsVertexSearch {
7433
7830
  }
7434
7831
  }
7435
7832
 
7436
- export { AccessoryImportances, Address, AdyenCardAxiosAdapter, AdyenPaymentMethodFactory, AntifraudBankSlipService, AntifraudCardService, AntifraudGlampointsService, AntifraudPixService, AntifraudProviderFactory, AntifraudProviders, Area, Authentication, AuthenticationFirebaseAuthService, AxiosAdapter, Base, BaseModel, BeardProblems, BeardSizes, BeautyProductImportances, BeautyProfile, BeautyQuestionsHelper, BillingStatus, BodyProblems, BodyShapes, BodyTattoos, BusinessError, BusinessUnitEnum, Buy2Win, Buy2WinFirestoreRepository, Campaign, CampaignBanner, CampaignDashboard, CampaignDashboardFirestoreRepository, CampaignHashtag, CampaignHashtagFirestoreRepository, Category, CategoryCollectionChildren, CategoryCollectionChildrenHasuraGraphQLRepository, CategoryFilter, CategoryFilterHasuraGraphQLRepository, CategoryFirestoreRepository, CategoryHasuraGraphQL, CategoryHasuraGraphQLRepository, CategoryProduct, CategoryProductHasuraGraphQLRepository, Checkout, CheckoutFirestoreRepository, CheckoutSubscription, CheckoutSubscriptionFirestoreRepository, CheckoutTypes, ClassNameHelper, ConnectBaseDocumentSnapshot, ConnectCollectionService, ConnectDocumentService, ConnectFirestoreService, Coupon, CouponCategories, CouponCategory, CouponChannels, CouponFirestoreRepository, CouponOldCategories, CouponSubtypes, CouponTypes, Debug, DebugDecoratorHelper, DebugHelper, DebugNamespaces, DuplicatedResultsError, Edition, EditionStatus, Exclusivities, FaceSkinOilinesses, FaceSkinProblems, FaceSkinTones, FamilyIncomes, Filter, FilterHasuraGraphQLRepository, FilterOption, FilterOptionHasuraGraphQLRepository, FilterType, FirebaseFileUploaderService, FragranceImportances, FraudValidationError, GenderDestination, GlampointsPaymentMethodFactory, GlampointsPaymentService, HairColors, HairProblems, HairStrands, HairTypes, Home, HomeFirestoreRepository, InvalidArgumentError, KitProduct, KitProductHasuraGraphQL, Lead, LeadFirestoreRepository, LegacyOrderFirestoreRepository, LineItem, Log, LogDocument, LogFirestoreRepository, Logger, NotFoundError, OfficePosition, Order, OrderBlocked, OrderBlockedFirestoreRepository, OrderBlockedType, OrderFirestoreRepository, OrderStatus, PagarmeBankSlipAxiosAdapter, PagarmeCardAxiosAdapter, PagarmePaymentMethodFactory, PagarmePaymentStatus, PagarmePixAxiosAdapter, Payment, PaymentError, PaymentFirestoreRepository, PaymentMethods, PaymentProviderFactory, PaymentProviders, PaymentTransaction, PaymentType, PersonTypes, Plans, Product, ProductErrors, ProductErrorsHasuraGraphQL, ProductErrorsHasuraGraphQLRepository, ProductFirestoreRepository, ProductHasuraGraphQL, ProductHasuraGraphQLRepository, ProductLabelEnum, ProductQueue, ProductQueueFirestoreRepository, ProductReview, ProductReviewHasuraGraphQLRepository, ProductSpents, ProductStockNotification, ProductStockNotificationHasuraGraphQLRepository, ProductVariantFirestoreRepository, ProductsIndex, ProductsVertexSearch, QuestionsFilters, RecoveryPassword, ReflectHelper, Register, RegisterFirebaseAuthService, RequiredArgumentError, RoundProductPricesHelper, Sequence, SequenceFirestoreRepository, ShippingMethod, ShopMenu, ShopMenuFirestoreRepository, ShopPageName, ShopSettings, ShopSettingsFirestoreRepository, Shops, SignInMethods, SignOut, Status, StockLimitError, StockOutError, Subscription, SubscriptionEditionFirestoreRepository, SubscriptionFirestoreRepository, SubscriptionMaterialization, SubscriptionMaterializationFirestoreRepository, SubscriptionPayment, SubscriptionPaymentFirestoreRepository, SubscriptionPlan, SubscriptionPlanFirestoreRepository, SubscriptionProductFirestoreRepository, SubscriptionSummary, SubscriptionSummaryFirestoreRepository, Trace, UnauthorizedError, UpdateOptionActions, UpdateUserImage, User, UserAddress, UserAddressFirestoreRepository, UserAlreadyRegisteredError, UserBeautyProfileFirestoreRepository, UserFirestoreRepository, UserPaymentMethod, UserPaymentMethodFirestoreRepository, UserType, Variant, VariantHasuraGraphQL, VariantHasuraGraphQLRepository, VertexAxiosAdapter, WeakPasswordError, Where, Wishlist, WishlistHasuraGraphQLRepository, WishlistLogType, getClass, is, isDebuggable, isUUID, parseDateTime, registerClass, resolveClass, withCreateFirestore, withCreateHasuraGraphQL, withCrudFirestore, withCrudHasuraGraphQL, withDeleteFirestore, withDeleteHasuraGraphQL, withFindFirestore, withFindHasuraGraphQL, withFirestore, withGetFirestore, withGetHasuraGraphQL, withHasuraGraphQL, withHelpers, withSubCollection, withUpdateFirestore, withUpdateHasuraGraphQL };
7833
+ export { AccessoryImportances, Address, AdyenCardAxiosAdapter, AdyenPaymentMethodFactory, AntifraudBankSlipService, AntifraudCardService, AntifraudGlampointsService, AntifraudPixService, AntifraudProviderFactory, AntifraudProviders, Area, Authentication, AuthenticationFirebaseAuthService, AxiosAdapter, Base, BaseModel, BeardProblems, BeardSizes, BeautyProductImportances, BeautyProfile, BeautyQuestionsHelper, BillingStatus, BodyProblems, BodyShapes, BodyTattoos, BusinessError, BusinessUnitEnum, Buy2Win, Buy2WinFirestoreRepository, Campaign, CampaignBanner, CampaignDashboard, CampaignDashboardFirestoreRepository, CampaignHashtag, CampaignHashtagFirestoreRepository, Category, CategoryCollectionChildren, CategoryCollectionChildrenHasuraGraphQLRepository, CategoryFilter, CategoryFilterHasuraGraphQLRepository, CategoryFirestoreRepository, CategoryHasuraGraphQL, CategoryHasuraGraphQLRepository, CategoryProduct, CategoryProductHasuraGraphQLRepository, Checkout, CheckoutFirestoreRepository, CheckoutSubscription, CheckoutSubscriptionFirestoreRepository, CheckoutTypes, ClassNameHelper, ConnectBaseDocumentSnapshot, ConnectCollectionService, ConnectDocumentService, ConnectFirestoreService, Coupon, CouponCategories, CouponCategory, CouponChannels, CouponFirestoreRepository, CouponOldCategories, CouponSubtypes, CouponTypes, Debug, DebugDecoratorHelper, DebugHelper, DebugNamespaces, DuplicatedResultsError, Edition, EditionStatus, Exclusivities, FaceSkinOilinesses, FaceSkinProblems, FaceSkinTones, FamilyIncomes, Filter, FilterHasuraGraphQLRepository, FilterOption, FilterOptionHasuraGraphQLRepository, FilterType, FirebaseFileUploaderService, FragranceImportances, FraudValidationError, GenderDestination, GlampointsPaymentMethodFactory, GlampointsPaymentService, HairColors, HairProblems, HairStrands, HairTypes, Home, HomeFirestoreRepository, InvalidArgumentError, KitProduct, KitProductHasuraGraphQL, Lead, LeadFirestoreRepository, LegacyOrderFirestoreRepository, LineItem, Log, LogDocument, LogFirestoreRepository, Logger, NotFoundError, OfficePosition, Order, OrderBlocked, OrderBlockedFirestoreRepository, OrderBlockedType, OrderFirestoreRepository, OrderStatus, PagarmeBankSlipAxiosAdapter, PagarmeCardAxiosAdapter, PagarmePaymentMethodFactory, PagarmePaymentStatus, PagarmePixAxiosAdapter, Payment, PaymentError, PaymentFirestoreRepository, PaymentMethods, PaymentProviderFactory, PaymentProviders, PaymentTransaction, PaymentType, PersonTypes, Plans, Product, ProductErrors, ProductErrorsHasuraGraphQL, ProductErrorsHasuraGraphQLRepository, ProductFirestoreRepository, ProductHasuraGraphQL, ProductHasuraGraphQLRepository, ProductLabelEnum, ProductReview, ProductReviewHasuraGraphQLRepository, ProductSpents, ProductStockNotification, ProductStockNotificationHasuraGraphQLRepository, ProductVariantFirestoreRepository, ProductsIndex, ProductsVertexSearch, QuestionsFilters, RecoveryPassword, ReflectHelper, Register, RegisterFirebaseAuthService, RequiredArgumentError, RestCacheAdapter, RoundProductPricesHelper, Sequence, SequenceFirestoreRepository, ShippingMethod, ShopMenu, ShopMenuFirestoreRepository, ShopPageName, ShopSettings, ShopSettingsFirestoreRepository, Shops, SignInMethods, SignOut, Status, StockLimitError, StockOutError, Subscription, SubscriptionEditionFirestoreRepository, SubscriptionFirestoreRepository, SubscriptionMaterialization, SubscriptionMaterializationFirestoreRepository, SubscriptionPayment, SubscriptionPaymentFirestoreRepository, SubscriptionPlan, SubscriptionPlanFirestoreRepository, SubscriptionProductFirestoreRepository, SubscriptionSummary, SubscriptionSummaryFirestoreRepository, Trace, UnauthorizedError, UpdateOptionActions, UpdateUserImage, User, UserAddress, UserAddressFirestoreRepository, UserAlreadyRegisteredError, UserBeautyProfileFirestoreRepository, UserFirestoreRepository, UserPaymentMethod, UserPaymentMethodFirestoreRepository, UserType, Variant, VariantHasuraGraphQL, VariantHasuraGraphQLRepository, VertexAxiosAdapter, WeakPasswordError, Where, Wishlist, WishlistHasuraGraphQLRepository, WishlistLogType, getClass, is, isDebuggable, isUUID, parseDateTime, registerClass, resolveClass, withCreateFirestore, withCreateHasuraGraphQL, withCrudFirestore, withCrudHasuraGraphQL, withDeleteFirestore, withDeleteHasuraGraphQL, withFindFirestore, withFindHasuraGraphQL, withFirestore, withGetFirestore, withGetHasuraGraphQL, withHasuraGraphQL, withHelpers, withSubCollection, withUpdateFirestore, withUpdateHasuraGraphQL };