import { CACHE_MODEL_METADATA } from "../core/decorator" ; import IORedis from "ioredis" ; import { defaultConfig } from "../config" ; export default class Rediser { static instance : Rediser ; static getInstance ( ) { if ( ! Rediser . instance ) { Rediser . instance = new Rediser ( ) ; } return Rediser . instance ; } private redisConnects : IORedis . Redis [ ] = [ ] ; async addConnect ( opts ) { const redis = new IORedis ( opts ) ; return new Promise ( ( resolve , reject ) => { redis . once ( "connect" , ( ) => { console . log ( `redis@${ opts ?. host }:${ opts ?. port } connected` . green ) ; this . redisConnects . push ( redis ) ; resolve ( redis ) ; } ) ; redis . on ( "error" , ( err ) => { throw err ; } ) ; } ) ; } async inject ( ) { const services = Reflect . getMetadata ( CACHE_MODEL_METADATA , Rediser ) ; if ( services ) { for ( const service of services ) { const { key , target , options } = service ; const opts = options || defaultConfig . redis ; target [ key ] = this . redisConnects . find ( ( v ) => v . connect . name === opts . name ) || ( await this . addConnect ( opts ) ) ; } } } }