import IORedis from "ioredis" ; import { Redis } from "../constants/Process" ; class RedisService { public readonly client : IORedis . Redis ; public constructor ( ) { this . client = new IORedis ( { host : Redis . HOST , port : Number ( Redis . PORT ) , username : Redis . USERNAME , password : Redis . PASSWORD , db : Number ( Redis . DB ) , } ) ; } public async set ( key , value , expire ? ) { if ( typeof expire !== "undefined" ) { return await this . client . set ( key , value , "EX" , expire ) ; } return await this . client . set ( key , value ) ; } public async get ( key ) { return await this . client . get ( key ) ; } public async del ( key ) { await this . client . del ( typeof key === "string" ? [ key ] : key ) ; } public async hmset ( key , value , expire ? ) { await this . client . hmset ( key , value ) ; if ( expire ) { await this . client . expire ( key , expire ) ; } } public hmget ( key , field ) ; public hmget ( key , field ) ; public async hmget ( key , field ) { if ( typeof field === "string" ) { return ( await this . client . hmget ( key , [ field ] ) ) [ 0 ] ; } return await this . client . hmget ( key , field ) ; } public async scan ( match , count = 100 , totalCount = false ) { const stream = this . client . scanStream ( { match , count , } ) ; const realCount = typeof totalCount === "boolean" ? count : totalCount ; let result = [ ] ; return new Promise ( ( resolve , reject ) => { stream . on ( "data" , data => { result = result . concat ( data as string ) ; if ( totalCount && result . length >= realCount ) { result . splice ( realCount ) ; stream . destroy ( ) ; } } ) ; stream . on ( "close" , ( ) => { resolve ( Array . from ( new Set ( result ) ) ) ; } ) ; stream . on ( "end" , ( ) => { resolve ( Array . from ( new Set ( result ) ) ) ; } ) ; stream . on ( "error" , reject ) ; } ) ; } public async mget ( keys ) { if ( keys . length === 0 ) { return [ ] ; } return await this . client . mget ( keys ) ; } public async vacantKey ( keys ) { const valueResult = await this . mget ( keys ) ; for ( let i = 0 ; i < valueResult . length ; i ++ ) { const value = valueResult [ i ] ; if ( value === null ) { return keys [ i ] ; } } return null ; } } export default new RedisService ( ) ;