Skip to content

Instantly share code, notes, and snippets.

@paztek
Created August 19, 2020 13:04
Show Gist options
  • Save paztek/0a6c537f48842424f08bbfedf928fa44 to your computer and use it in GitHub Desktop.
Save paztek/0a6c537f48842424f08bbfedf928fa44 to your computer and use it in GitHub Desktop.
nestjs-redis-example-2
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;
};
});
}
}
@kasir-barati
Copy link

Hello @paztek, How can I use ConfigService instead of hard coded values. I like to use useClass instead of useFactory

// ....
        BaseCacheModule.registerAsync({
            useFactory: () => {
                return {
                    store: redisStore,
                    host: 'localhost',
                    port: 6379,
                }
            },
        }),
// ....

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment