Skip to content

Instantly share code, notes, and snippets.

@paztek
Last active March 30, 2022 09:34
Show Gist options
  • Save paztek/ba60ba1e1f6ed7c41f2b44c2f7e8a1e8 to your computer and use it in GitHub Desktop.
Save paztek/ba60ba1e1f6ed7c41f2b44c2f7e8a1e8 to your computer and use it in GitHub Desktop.
nestjs-redis-example-1
import { Body, Controller, Get, Put } from '@nestjs/common';
import { AppService } from './app.service';
@Controller('/hello')
export class AppController {
constructor(
private readonly appService: AppService,
) {}
@Put()
async putHello(@Body() { name }: { name: string }): Promise<string> {
await this.appService.setHello(name);
return name;
}
@Get()
getHello(): Promise<string> {
return this.appService.getHello();
}
}
import { CACHE_MANAGER, CacheModule, Inject, Module, OnModuleDestroy } from '@nestjs/common';
import * as redisStore from 'cache-manager-ioredis';
import { Cache } from 'cache-manager'
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { Redis } from 'ioredis';
@Module({
imports: [
CacheModule.registerAsync({
useFactory: () => {
return {
store: redisStore,
host: 'localhost',
port: 6379,
}
},
}),
],
controllers: [
AppController,
],
providers: [
AppService,
],
})
export class AppModule {}
import { CACHE_MANAGER, Inject, Injectable } from '@nestjs/common';
import { Cache } from 'cache-manager';
const KEY = 'hello';
@Injectable()
export class AppService {
constructor(
@Inject(CACHE_MANAGER) private readonly cache: Cache,
) {}
async setHello(name: string): Promise<void> {
await this.cache.set(KEY, name, { ttl: 3600 });
}
async getHello(): Promise<string> {
const name = await this.cache.get(KEY) || 'matthieu';
return `Hello ${name}!`;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment