Commit 1455c533 authored by Fauzi Fadhillah's avatar Fauzi Fadhillah
Browse files

Merge commit 'db5200c4' into v3.1.5

parents d05c1c33 db5200c4
Loading
Loading
Loading
Loading
+1 −4
Original line number Diff line number Diff line
@@ -31,10 +31,7 @@ export declare class Model<TAttributes extends {} = any, TCreate extends {} = TA
    private static rejectOnEmptyMode;
    static findAllCache<T extends Model>(this: {
        new (): T;
    }, options?: FindAllNestedOptionsCache<T['_attributes']>): Promise<T[]>;
    static findAllCache<T extends Model>(this: {
        new (): T;
    }, options?: FindAllOptionsCache<T['_attributes']>): Promise<T[]>;
    }, options: FindAllNestedOptionsCache<T['_attributes']>): Promise<T[]>;
    static scopes<M extends SequelizeModel>(this: ModelStatic<M>, options?: string | ScopeOptions | readonly (string | ScopeOptions)[] | WhereAttributeHash<M>): typeof Model & {
        new (): M;
    };
+7 −25
Original line number Diff line number Diff line
@@ -2,7 +2,6 @@
Object.defineProperty(exports, "__esModule", { value: true });
exports.Model = void 0;
const common_1 = require("@nestjs/common");
const date_utility_1 = require("../date-utility");
const lodash_1 = require("lodash");
const crypto = require("crypto");
const sequelize_cache_1 = require("./sequelize-cache");
@@ -113,38 +112,21 @@ class Model extends sequelize_typescript_1.Model {
            throw options.rejectOnEmpty;
        }
    }
    static async findAllCache(options = {}) {
    static async findAllCache(options) {
        const TTL = options?.ttl || this['modelTTL'] || sequelize_cache_1.SequelizeCache.defaultTTL;
        delete options?.ttl;
        const maxUpdateOptions = getMaxUpdateOptions(options);
        const onUpdateAttribute = this['getAttributes']()?.[this['onUpdateAttribute']];
        const maxUpdatedAtPromise = onUpdateAttribute?.field
            ? getCustomCache({ key: 'max', maxUpdateOptions, model: `${this.name}` }, 2, () => (this['max'](`${this.name}.${onUpdateAttribute?.field}`, maxUpdateOptions)))
            : undefined;
        const [maxUpdatedAt, count] = await Promise.all([
            maxUpdatedAtPromise,
            this['countCache'](2, options),
        ]);
        if (!count && !maxUpdatedAt)
            return TransformCacheToModels(this, '[]');
        const max = date_utility_1.DateUtility.convertDateTimeToEpoch(new Date(maxUpdatedAt)) + +count;
        const scope = (0, lodash_1.cloneDeep)(this['_scope']);
        const defaultOptions = this['_defaultsOptions'](options, scope);
        const keyOpts = cache_utilty_1.default.setQueryOptions(defaultOptions);
        const keyTime = cache_utilty_1.default.setKey(this.name, keyOpts);
        let timeCached = await sequelize_cache_1.SequelizeCache.catchGetter({ key: keyTime });
        let canFetch = false;
        if (!timeCached || max.toString() != timeCached) {
            canFetch = true;
            await sequelize_cache_1.SequelizeCache.catchSetter({ key: keyTime, value: max.toString(), ttl: TTL });
            timeCached = max.toString();
        }
        const keyModel = cache_utilty_1.default.setKey(this.name, timeCached, keyOpts);
        const keyModel = cache_utilty_1.default.setKey(this.name, keyOpts);
        let modelString = await sequelize_cache_1.SequelizeCache.catchGetter({ key: keyModel });
        if (canFetch || !modelString) {
        if (!modelString) {
            const newModels = await this['findAll'](options);
            if (!newModels?.length) {
                return [];
            }
            modelString = JSON.stringify(newModels);
            const newKeyModel = cache_utilty_1.default.setKey(this.name, max, keyOpts);
            const newKeyModel = cache_utilty_1.default.setKey(this.name, keyModel);
            sequelize_cache_1.SequelizeCache.catchSetter({ key: newKeyModel, value: modelString, ttl: TTL });
        }
        const include = options && 'include' in options ? options?.include : undefined;
+8 −43
Original line number Diff line number Diff line
@@ -258,71 +258,36 @@ export class Model<TAttributes extends {} = any, TCreate extends {} = TAttribute
  }

  static async findAllCache<T extends Model>(this: { new(): T },
    options?: FindAllNestedOptionsCache<T['_attributes']>,
  ): Promise<T[]> 
  static async findAllCache<T extends Model>(this: { new(): T },
    options?: FindAllOptionsCache<T['_attributes']>,
  ): Promise<T[]> 
  static async findAllCache<T extends Model>(this: { new(): T },
    options: FindAllNestedOptionsCache<T['_attributes']> | FindAllOptionsCache<T['_attributes']> = {},
    options: FindAllNestedOptionsCache<T['_attributes']>,
  ): Promise<T[]> 
  {

    const TTL = options?.ttl || this['modelTTL'] || SequelizeCache.defaultTTL
    delete options?.ttl

    const maxUpdateOptions = getMaxUpdateOptions(options);

    const onUpdateAttribute = this['getAttributes']()?.[this['onUpdateAttribute']];
    const maxUpdatedAtPromise = onUpdateAttribute?.field
    ? getCustomCache(
    { key: 'max', maxUpdateOptions, model: `${this.name}` }, 
    2, 
    () => (this['max'](`${this.name}.${onUpdateAttribute?.field}`, maxUpdateOptions))) 
    : undefined

    // get max updatedAt on model
    const [maxUpdatedAt, count] = await Promise.all([
      maxUpdatedAtPromise,
      this['countCache'](2, options),
    ])

    if (!count && !maxUpdatedAt) return TransformCacheToModels(this, '[]')

    const max = DateUtility.convertDateTimeToEpoch(new Date(maxUpdatedAt)) + +count

    const scope = cloneDeep(this['_scope'])

    const defaultOptions = this['_defaultsOptions'](options, scope)
    // setting up key for FindOptions
    const keyOpts = CacheUtility.setQueryOptions(defaultOptions);

    // get what time is cached on this model based on keyOpts
    const keyTime = CacheUtility.setKey(this.name, keyOpts)
    let timeCached = await SequelizeCache.catchGetter({ key: keyTime })

    let canFetch = false
    // set time cache if timeCached is null
    if (!timeCached || max.toString() != timeCached) {
      canFetch = true

      await SequelizeCache.catchSetter({ key: keyTime, value: max.toString(), ttl: TTL })
      timeCached = max.toString()
    }

    // set key for get model
    const keyModel = CacheUtility.setKey(this.name, timeCached, keyOpts)
    const keyModel = CacheUtility.setKey(this.name, keyOpts)
    // get the model result based on key
    let modelString = await SequelizeCache.catchGetter({ key: keyModel })

    // check if result is null or can fetch
    // then can fetch row on database
    if (canFetch || !modelString) {
    if (!modelString) {
      // fetch row on models
      const newModels = await this['findAll'](options)
      if (!newModels?.length) {
        return [];
      }
      modelString = JSON.stringify(newModels)

      // set cache model based on new key
      const newKeyModel = CacheUtility.setKey(this.name, max, keyOpts)
      const newKeyModel = CacheUtility.setKey(this.name, keyModel)
      SequelizeCache.catchSetter({ key: newKeyModel, value: modelString, ttl: TTL })
    }