Skip to content

Commit

Permalink
Merge pull request #28 from Bricks666/feature/cache-policy
Browse files Browse the repository at this point in the history
Feature/cache policy
  • Loading branch information
Bricks666 authored Mar 25, 2024
2 parents 5571018 + 50bfeca commit 52d8901
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 6 deletions.
2 changes: 1 addition & 1 deletion src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ const modules = [
store: redisStore as unknown as CacheStore,
isGlobal: true,
max: 50,
ttl: 5,
ttl: +process.env.CACHE_TTL,
url: process.env.REDIS_URL,
}),
ConfigModule.forRoot({
Expand Down
3 changes: 3 additions & 0 deletions src/rooms/controllers/lib.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export const getUserRoomsCacheKey = (userId: number): string => {
return `rooms_${userId}`;
};
27 changes: 22 additions & 5 deletions src/rooms/controllers/rooms.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ import {
Body,
Put,
Delete,
UseInterceptors
UseInterceptors,
Inject
} from '@nestjs/common';
import {
ApiBody,
Expand All @@ -16,7 +17,7 @@ import {
ApiParam,
ApiTags
} from '@nestjs/swagger';
import { CacheInterceptor } from '@nestjs/cache-manager';
import { CACHE_MANAGER, Cache, CacheInterceptor } from '@nestjs/cache-manager';
import { Auth, CurrentUser } from '@/auth/lib';
import { SecurityUserDto } from '@/users/dto';
import { IntParam } from '@/shared';
Expand All @@ -25,12 +26,16 @@ import { RoomsService } from '../services';
import { CreateRoomDto, RoomDto, UpdateRoomDto } from '../dto';
import { IsOwner } from '../lib';
import { WithRights } from '../types';
import { getUserRoomsCacheKey } from './lib';

@ApiTags('Комнаты')
@Controller('rooms')
@Auth()
export class RoomsController {
constructor(private readonly roomsService: RoomsService) {}
constructor(
private readonly roomsService: RoomsService,
@Inject(CACHE_MANAGER) private readonly cacheManager: Cache
) {}

@ApiOperation({
summary: 'Возврат всех комнат авторизованного пользователя',
Expand All @@ -41,12 +46,24 @@ export class RoomsController {
description: 'Все комнаты, в которых состоит пользователь',
})
@Get('/')
@UseInterceptors(CacheInterceptor)
async getAll(
@CurrentUser() user: SecurityUserDto
): Promise<WithRights<RoomDto>[]> {
const { id, } = user;
return this.roomsService.getAll({ userId: id, });

const cacheKey = getUserRoomsCacheKey(id);

let rooms = await this.cacheManager.get<WithRights<RoomDto>[]>(cacheKey);

if (rooms) {
return rooms;
}

rooms = await this.roomsService.getAll({ userId: id, });

await this.cacheManager.set(cacheKey, rooms, +process.env.CACHE_TTL);

return rooms;
}

@ApiOperation({
Expand Down

0 comments on commit 52d8901

Please sign in to comment.