caching.module.ts 1.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
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 {}