Created
August 31, 2021 15:17
-
-
Save meeech/ce3db22ec39de56b75dee69dcc54ab94 to your computer and use it in GitHub Desktop.
Register dynamic module with some error handling nestjs
This file contains 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
@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