Skip to content

Instantly share code, notes, and snippets.

@meeech
Created August 31, 2021 15:17
Show Gist options
  • Save meeech/ce3db22ec39de56b75dee69dcc54ab94 to your computer and use it in GitHub Desktop.
Save meeech/ce3db22ec39de56b75dee69dcc54ab94 to your computer and use it in GitHub Desktop.
Register dynamic module with some error handling nestjs
@Module({
imports: [
CacheModule.registerAsync({
imports: [ConfigModule],
useFactory: async (
cConfig: ConfigType<typeof cacheConfig>,
rConfig: ConfigType<typeof redisConfig>,
) => {
Logger.log(`*** Cache is disabled: ${cConfig.disabled}`);
// Attempt to connect...
const rClient = new Redis({ lazyConnect: true, ...rConfig });
// Set up the error handler. If we lose redis connection, the site will still work
// Just the route cache-manager will automatically be disabled
rClient.on('error', (err) => {
Logger.log(`Can't connect to redis: ${err}. Cache will be disabled.`);
rClient.quit();
});
const redisAvailable = await rClient
.connect()
.then(() => {
return true;
})
.catch((reason) => {
Logger.log(
`Could not connect to redis, disabling cache: ${reason}`,
);
return false;
});
return {
store: !redisAvailable || cConfig.disabled ? 'none' : redisStore,
db: rConfig.db,
host: rConfig.host,
port: rConfig.port,
redisInstance: rClient,
ttl: cConfig.ttl_seconds,
};
},
inject: [cacheConfig.KEY, redisConfig.KEY],
}),
],
exports: [CacheModule],
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment