import { CacheModule, Module } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import * as redisStore from 'cache-manager-redis-store';
import { notNilEmpty } from 'qx-util';
import { CachingService } from './caching.service';

/**
 * 高速缓存模块
 *
 * @author chitanda
 * @date 2021-08-18 21:08:12
 * @export
 * @class CachingModule
 */
@Module({
  exports: [CacheModule, CachingService],
  imports: [
    CacheModule.registerAsync({
      imports: [ConfigModule],
      useFactory: async (configService: ConfigService) => {
        const caching = configService.get('caching');
        const redis = configService.get('redis');
        if (redis.enable) {
          return {
            store: redisStore,
            host: redis.host,
            port: redis.port,
            ttl: caching.ttl,
            db: notNilEmpty(redis.db) ? redis.db : undefined,
            auth_pass: notNilEmpty(redis.auth_pass) ? redis.auth_pass : undefined,
          };
        }
        return {
          ttl: caching.ttl,
        };
      },
      inject: [ConfigService],
    }),
  ],
  providers: [CachingService],
})
export class CachingModule {}
