import { Injectable, OnModuleInit } from '@nestjs/common';
// import { ClientRedis, Client } from '@nestjs/microservices';
// import { redisClientOptions } from './redis.options';
import { RedisService as CacheService } from 'nestjs-redis';

@Injectable()
export class RedisService implements OnModuleInit {
  public client;
  constructor(private redisService: CacheService) {}
  async onModuleInit() {
    console.log('redis init');
    try {
      this.getClient();
    } catch (error) {
      console.error('error', error);
    }
  }

  async getClient() {
    this.client = await this.redisService.getClient();
  }

  public async set(key: string, value: any, seconds?: number) {
    value = JSON.stringify(value);
    if (!this.client) {
      await this.getClient();
    }
    if (!seconds) {
      await this.client.set(key, value);
    } else {
      await this.client.set(key, value, 'EX', seconds);
    }
  }

  //获取值的方法
  public async get(key: string) {
    if (!this.client) {
      await this.getClient();
    }
    const data = await this.client.get(key);
    if (!data) return;
    return JSON.parse(data);
  }

  //获取值的方法
  public async del(key: string) {
    if (!this.client) {
      await this.getClient();
    }
    await this.client.del(key);
  }
  // 清理缓存
  public async flushall(): Promise<any> {
    if (!this.client) {
      await this.getClient();
    }

    await this.client.flushall();
  }
}
