Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: update user ranking data for every 10minute #56 #58

Merged
merged 3 commits into from
Dec 5, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion BE-config
49 changes: 49 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
"@nestjs/passport": "^10.0.2",
"@nestjs/platform-express": "^9.0.0",
"@nestjs/platform-socket.io": "^9.4.3",
"@nestjs/schedule": "^4.0.0",
"@nestjs/swagger": "^7.1.16",
"@nestjs/typeorm": "^10.0.0",
"@nestjs/websockets": "^9.4.3",
Expand Down
2 changes: 2 additions & 0 deletions src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import redisConfig from './config/redis.config';
import typeOrmConfig from './config/typeorm.config';
import { GameModule } from './game/game.module';
import { UsersModule } from './users/users.module';
import { ScheduleModule } from '@nestjs/schedule';

@Module({
imports: [
Expand Down Expand Up @@ -43,6 +44,7 @@ import { UsersModule } from './users/users.module';
useFactory: (redisConfigure: ConfigType<typeof redisConfig>) =>
redisConfigure,
}),
ScheduleModule.forRoot(),
AuthModule,
UsersModule,
GameModule,
Expand Down
7 changes: 4 additions & 3 deletions src/app.service.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
import { Injectable } from '@nestjs/common';
import { InjectRedis } from '@liaoliaots/nestjs-redis';
import { Redis } from 'ioredis';

import { Logger } from '@nestjs/common';
@Injectable()
export class AppService {
constructor(@InjectRedis() private readonly redis: Redis) {}

// push data to redis using zadd
async updateRanking(id: number, score: number) {
await this.redis.zadd('rankings', score, `user:${id}`);
async updateRanking(score: number, id: number) {
Logger.log(`Redis updateRanking: ${score}, ${id}`)
await this.redis.zadd('rankings', score, id);
}
}
10 changes: 7 additions & 3 deletions src/auth/auth.controller.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Body, Controller, Patch, Post, Res, UseGuards } from '@nestjs/common';
import { AppService } from './../app.service';
import { Body, Controller, Logger, Patch, Post, Res, UseGuards } from '@nestjs/common';
import { ApiOperation, ApiParam, ApiResponse, ApiTags } from '@nestjs/swagger';
import { Response } from 'express';
import { User } from 'src/users/entities/user.entity';
Expand All @@ -17,6 +18,7 @@ export class AuthController {
private readonly authService: AuthService,
private readonly ftAuthService: FtAuthService,
private readonly usersService: UsersService,
private readonly AppService: AppService,
) {}

@Post('/signin')
Expand Down Expand Up @@ -127,7 +129,7 @@ export class AuthController {
}

const user = await this.usersService.createUser(nickname, 'test@test');

const { jwtAccessToken, jwtRefreshToken } =
await this.authService.generateJwtToken(user);

Expand All @@ -152,6 +154,8 @@ export class AuthController {
isMfaEnabled: false,
mfaCode: undefined,
};
Logger.log(`updateRanking(ladderScore, id): ${user.ladderScore}, ${user.id}`);
await this.AppService.updateRanking(user.ladderScore, user.id);

return res.send(userSigninResponseDto);
}
Expand All @@ -162,7 +166,7 @@ export class AuthController {
description:
'200 OK 만 반환한다. 쿠키에 있는 access,refresh token를 지운다.',
})
@UseGuards(JwtAuthGuard)
@UseGuards(JwtAuthGuard)
async signout(@GetUser() user: User, @Res() res: Response) {
await this.usersService.signout(user.id);

Expand Down
33 changes: 19 additions & 14 deletions src/users/ranks.service.ts
Original file line number Diff line number Diff line change
@@ -1,34 +1,30 @@
import { AppService } from 'src/app.service';
import { InjectRedis } from '@liaoliaots/nestjs-redis';
import { BadRequestException, Injectable } from '@nestjs/common';
import { BadRequestException, Injectable, Logger } from '@nestjs/common';
import { Redis } from 'ioredis';
import { UsersRepository } from 'src/users/users.repository';
import { RankUserResponseDto } from './dto/rank-user-response.dto';
import { RankUserReturnDto } from './dto/rank-user-return.dto';

import { Cron, CronExpression } from '@nestjs/schedule';
@Injectable()
export class RanksService {
constructor(
private readonly userRepository: UsersRepository,
private readonly AppService: AppService,
@InjectRedis() private readonly redis: Redis,
) {}

async findRanksWithPage(page: number): Promise<RankUserResponseDto> {
//userIDRanking: [userId, userId, userId, ...]
// const userRanking: string[] = await this.redis.zrange(
// 'rankings',
// (page - 1) * 10,
// page * 10 - 1,
// );
const userRanking = await this.redis.zrange(


const userRanking = await this.redis.zrevrange(
'rankings',
(page - 1) * 10,
page * 10 - 1,
);

if (!userRanking) {
throw new BadRequestException(`unavailable ranking property`);
}
console.log('userRanking: ', userRanking); // dbg
console.log('userranking', userRanking); // ok

const foundUsers = await this.userRepository.findRanksInfos(
userRanking,
Expand All @@ -39,12 +35,21 @@ export class RanksService {
// userID 배열을 가지고 유저 정보를 조회
// 유저 정보에 ranking 프로퍼티를 추가 ( redis에서 조회한 ranking을 넣어줌)

const rankUsers: RankUserReturnDto[] = foundUsers.map((user) => ({
const rankUsers: RankUserReturnDto[] = foundUsers.map((user, index) => ({
...user,
ranking: Number(userRanking),
ranking: index + 1 + (page - 1) * 10,
}));
const totalItemCount = await this.userRepository.count(); // TODO: redis에 저장된 총 유저 수를 가져와야 하지 않을까?

return { rankUsers, totalItemCount };
}

@Cron(CronExpression.EVERY_MINUTE)
async handleCron() {
const users = await this.userRepository.find();
for (const user of users) {
Logger.log(`updateRanking: ${user.ladderScore}, ${user.id}`);
await this.AppService.updateRanking(user.ladderScore, user.id);
}
}
}
2 changes: 1 addition & 1 deletion src/users/users.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,7 @@ export class UsersController {
summary: '유저 차단목록 조회',
description: 'pagination된 차단 유저 목록을 제공합니다.',
})
@ApiResponse({ status: 500, description: '쿼리에러' })
@ApiResponse({ status: 400, description: '쿼리에러' })
async findBlockListWithPage(
@GetUser() user: User,
@Query('page', ParseIntPipe, PositiveIntPipe) page: number,
Expand Down
8 changes: 7 additions & 1 deletion src/users/users.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,14 @@ import { RanksService } from './ranks.service';
import { UsersController } from './users.controller';
import { UsersRepository } from './users.repository';
import { UsersService } from './users.service';
import { ScheduleModule } from '@nestjs/schedule';
import { AppService } from 'src/app.service';

@Module({
imports: [TypeOrmModule.forFeature([User, Friend, Block, Game])],
imports: [
TypeOrmModule.forFeature([User, Friend, Block, Game]),
ScheduleModule.forRoot(),
],
controllers: [UsersController],
providers: [
UsersService,
Expand All @@ -26,6 +31,7 @@ import { UsersService } from './users.service';
FriendsRepository,
BlocksRepository,
GameRepository,
AppService,
],
exports: [UsersService],
})
Expand Down
41 changes: 23 additions & 18 deletions src/users/users.repository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,29 +72,34 @@ export class UsersRepository extends Repository<User> {
}

async findRanksInfos(users: string[]) {
const rankUsers = await this.find({
select: ['nickname', 'avatar', 'ladderScore'],
where: {
id: In(users),
},
});
if (!rankUsers) {
throw new BadRequestException(
`there is no user with nickname ${users}`,
);
const rankUsers: User[] = [];
// Use forEach to iterate through users array
for (const userid of users) {
const user = await this.findOne({
select: [
'nickname',
'avatar',
'ladderScore',
],
where: { id: parseInt(userid) },
});
if (!user) {
throw new BadRequestException(`there is no user with id`);
}
rankUsers.push(user);
}
return rankUsers;
}
}

async initAllSocketIdAndUserStatus() {
await this.update(
{},
{
status: UserStatus.OFFLINE,
channelSocketId: null,
await this.createQueryBuilder()
.update()
.set({
gameSocketId: null,
},
);
channelSocketId: null,
status: UserStatus.OFFLINE,
})
.execute();
}

// async findChannelSocketIdByUserId(userId: number) {
Expand Down
Loading