Created
February 20, 2020 20:48
-
-
Save kyle-mccarthy/b6770b49ebfab88e75bcbac87b272a94 to your computer and use it in GitHub Desktop.
nest.js cache config for redis
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { | |
CacheModuleOptions, | |
CacheOptionsFactory, | |
Injectable, | |
} from '@nestjs/common'; | |
import { LoggerService } from '@src/common/logger.service'; | |
import { ConfigOptions, ConfigService } from '@src/config/config.service'; | |
import * as redisCacheStore from 'cache-manager-redis-store'; | |
@Injectable() | |
export class CacheConfigService implements CacheOptionsFactory { | |
constructor( | |
private configService: ConfigService, | |
private logger: LoggerService, | |
) {} | |
retryStrategy() { | |
return { | |
retry_strategy: (options: any) => { | |
if (options.error && options.error.code === 'ECONNREFUSED') { | |
// End reconnecting on a specific error and flush all commands with | |
// a individual error | |
this.logger.error( | |
'The server refused the connection', | |
{}, | |
'node-redis', | |
); | |
return new Error('The server refused the connection'); | |
} | |
if (options.total_retry_time > 1000 * 60) { | |
// End reconnecting after a specific timeout and flush all commands | |
// with a individual error | |
this.logger.error('Retry time exhausted', {}, 'node-redis'); | |
return new Error('Retry time exhausted'); | |
} | |
if (options.attempt > 2) { | |
// End reconnecting with built in error | |
this.logger.error('Max attempts exhausted', {}, 'node-redis'); | |
return new Error('Max attempts exhausted'); | |
} | |
// reconnect after | |
return Math.min(options.attempt * 100, 3000); | |
}, | |
}; | |
} | |
createCacheOptions(): CacheModuleOptions { | |
return { | |
store: redisCacheStore, | |
host: this.configService.get(ConfigOptions.REDIS_HOST), | |
port: this.configService.get(ConfigOptions.REDIS_PORT), | |
auth_pass: this.configService.get(ConfigOptions.REDIS_AUTH), | |
...this.retryStrategy(), | |
}; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
nice br0