Skip to content

Instantly share code, notes, and snippets.

@SOHELAHMED7
Last active September 14, 2023 14:55
Show Gist options
  • Save SOHELAHMED7/f7396fb7711aad9538e149e1b811b53c to your computer and use it in GitHub Desktop.
Save SOHELAHMED7/f7396fb7711aad9538e149e1b811b53c to your computer and use it in GitHub Desktop.
Nestjs redis cache example
import { Controller, Get } from '@nestjs/common';
import { AppService } from './app.service';
@Controller()
export class AppController {
constructor(private readonly appService: AppService) {}
@Get()
getHello(): Promise<string> {
return this.appService.getHello();
}
}
import { Injectable, Inject, CACHE_MANAGER } from '@nestjs/common';
import { Cache } from 'cache-manager';
// https://stackoverflow.com/questions/55156379/how-to-control-cache-in-nestjs
@Injectable()
export class AppService {
constructor(@Inject(CACHE_MANAGER) private cacheManager: Cache) {
}
async getHello(): Promise<string> {
// console.log(typeof this.cacheManager);
// console.log(this.cacheManager);
// callback way
// this.cacheManager.set('foo', 'bar', {ttl: 100000}, (err) => {
// // console.log(err);
// this.cacheManager.get('foo', (err, result) => {
// // console.log('inner error', err);
// console.log(result);
// });
// });
// async/await way
await this.cacheManager.set('foo2', 'bar2', {ttl: 100000});
const res = await this.cacheManager.get('foo2');
console.log(res); // logs "bar2"
return 'Hello World! 222';
}
}
@kasir-barati
Copy link

@SOHELAHMED7 Why did not you mention that how we should config it in our app.module.ts? I guess we have to configure it like this:

@Module({
    imports: [
        ConfigModule.forRoot({
            isGlobal: true,
            load: [configuration],
        }),
        CacheModule.register<RedisOptions>({
            isGlobal: true,
            store: redisStore,
            host: process.env.REDIS_HOST,
            port: +process.env.REDIS_PORT,
        })
    ],
    controllers: [AppController],
    providers: [AppService, AllHttpExceptionsFilter],
})
export class AppModule {}

TBH even I think this is not cache-manager configuration.

@SOHELAHMED7
Copy link
Author

It is already present. Pleas see "Redis Cache" section after "Installing Dependencies" at https://sohelahmed.site/blog/redis-cache-in-nest-js

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