import { CACHE_MANAGER, Inject, Injectable } from '@nestjs/common';
import { Cache, CachingConfig, Store, WrapArgsType } from 'cache-manager';

/**
 * 缓存中间类
 *
 * @author chitanda
 * @date 2021-08-18 21:08:24
 * @export
 * @class CachingService
 */
@Injectable()
export class CachingService {
  /**
   * 缓存实例
   *
   * @author chitanda
   * @date 2021-08-18 22:08:30
   * @readonly
   * @type {Store}
   */
  get store(): Store {
    return this.cacheManager.store;
  }

  /**
   * Creates an instance of CachingService.
   *
   * @author chitanda
   * @date 2021-08-18 22:08:03
   * @param {Cache} cacheManager
   */
  constructor(@Inject(CACHE_MANAGER) private readonly cacheManager: Cache) {}

  /**
   * 设置缓存
   *
   * @author chitanda
   * @date 2021-08-18 22:08:02
   * @param {string} key
   * @param {unknown} val
   * @param {CachingConfig} opts?
   * @return {*}
   */
  set(key: string, val: unknown, opts?: CachingConfig): Promise<unknown> {
    return this.cacheManager.set(key, val, opts);
  }

  /**
   * 获取缓存
   *
   * @author chitanda
   * @date 2021-08-18 22:08:09
   * @param {string} key
   * @return {*}  {Promise<unknown>}
   */
  get(key: string): Promise<unknown> {
    return this.cacheManager.get(key);
  }

  /**
   * 删除缓存
   *
   * @author chitanda
   * @date 2021-08-18 22:08:34
   * @param {string} key
   * @return {*}  {Promise<unknown>}
   */
  del(key: string): Promise<unknown> {
    return this.cacheManager.del(key);
  }

  /**
   * 重置
   *
   * @author chitanda
   * @date 2021-08-18 22:08:34
   * @return {*}  {Promise<void>}
   */
  reset(): Promise<void> {
    return this.cacheManager.reset();
  }

  wrap(...args: WrapArgsType<unknown>[]): Promise<unknown> {
    return this.cacheManager.wrap(...args);
  }
}
