Created
August 19, 2020 13:04
-
-
Save paztek/0a6c537f48842424f08bbfedf928fa44 to your computer and use it in GitHub Desktop.
nestjs-redis-example-2
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 { | |
CACHE_MANAGER, | |
CacheModule as BaseCacheModule, | |
Inject, | |
Logger, | |
Module, | |
OnModuleInit, | |
} from '@nestjs/common'; | |
import * as redisStore from 'cache-manager-ioredis'; | |
import { Cache} from 'cache-manager'; | |
@Module({ | |
imports: [ | |
BaseCacheModule.registerAsync({ | |
useFactory: () => { | |
return { | |
store: redisStore, | |
host: 'localhost', | |
port: 6379, | |
} | |
}, | |
}), | |
], | |
exports: [ | |
BaseCacheModule, | |
], | |
}) | |
export class CacheModule implements OnModuleInit { | |
constructor( | |
@Inject(CACHE_MANAGER) private readonly cache: Cache | |
) {} | |
public onModuleInit(): any { | |
const logger = new Logger('Cache'); | |
// Commands that are interesting to log | |
const commands = [ | |
'get', | |
'set', | |
'del', | |
]; | |
const cache = this.cache; | |
commands.forEach((commandName) => { | |
const oldCommand = cache[commandName]; | |
cache[commandName] = async (...args) => { | |
// Computes the duration | |
const start = new Date(); | |
const result = await oldCommand.call(cache, ...args); | |
const end = new Date(); | |
const duration = end.getTime() - start.getTime(); | |
// Avoid logging the options | |
args = args.slice(0, 2); | |
logger.log(`${commandName.toUpperCase()} ${args.join(', ')} - ${duration}ms`); | |
return result; | |
}; | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hello @paztek, How can I use ConfigService instead of hard coded values. I like to use
useClass
instead ofuseFactory