Skip to content

Commit

Permalink
Merge pull request #174 from boostcampwm2023/feat/deserialize-user-db
Browse files Browse the repository at this point in the history
  • Loading branch information
Daehyun Kim authored Dec 7, 2023
2 parents 7e109a6 + 3e36d9a commit ef3489b
Show file tree
Hide file tree
Showing 8 changed files with 50 additions and 75 deletions.
9 changes: 4 additions & 5 deletions server/src/app.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,11 +34,10 @@ export class AppController {

if (user && isUserSession(user)) {
const userSession: UserSession = { ...(req.user as User) } as UserSession;
const room = await this.roomService.findRoomParticipating(user);
this.logger.debug(
`The current user is participating in room: ${room?.code}`,
);
userSession.participatingRoomCode = room?.code;
const joinedRooms = await this.roomService.findJoinedRooms(user);
if (joinedRooms.length > 0) {
userSession.participatingRoomCode = joinedRooms[0].room?.code;
}
return userSession;
}

Expand Down
4 changes: 1 addition & 3 deletions server/src/auth/auth.serializer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,6 @@ export class LocalSerializer extends PassportSerializer {
throw new BadRequestException('User not found!');
}

// TODO: change userSession to user later. 20231206
// e.g.: return done(null, user);
return done(null, userSession);
return await done(null, user);
}
}
11 changes: 8 additions & 3 deletions server/src/auth/auth.service.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
import { Injectable, Logger } from '@nestjs/common';
import {
Injectable,
InternalServerErrorException,
Logger,
} from '@nestjs/common';
import { UserService } from '../user/user.service';
import User from '../entities/user.entity';
import { ProviderInfo } from 'src/types/user';
Expand All @@ -18,9 +22,10 @@ export class AuthService {
await this.userService.findUserByProviderInfo(mockProviderInfo);

if (user == null) {
this.logger.debug(`Mock user ${username} not found!`);
throw new Error('Mock user not found');
this.logger.debug('유저가 존재하지 않습니다.');
throw new InternalServerErrorException();
}

return user;
}
}
4 changes: 1 addition & 3 deletions server/src/entities/room.entity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,9 +47,7 @@ export default class Room extends BaseEntity {
})
host?: User;

@OneToMany(() => RoomUser, (roomUser) => roomUser.room, {
cascade: ['remove'],
})
@OneToMany(() => RoomUser, (roomUser) => roomUser.room)
joinedUsers?: RoomUser[];

@OneToMany(() => Submission, (submission) => submission.room)
Expand Down
4 changes: 2 additions & 2 deletions server/src/entities/user.entity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,9 +41,9 @@ export default class User extends BaseEntity {
deletedAt?: Date;

@OneToMany(() => RoomUser, (roomUser) => roomUser.user, {
cascade: ['remove'],
lazy: true,
})
joinedRooms?: RoomUser[];
joinedRooms?: Promise<RoomUser[]>;

@OneToMany(() => Submission, (submission) => submission.user)
submissions?: Submission[];
Expand Down
3 changes: 3 additions & 0 deletions server/src/room/room.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,17 @@ import {
Logger,
Post,
Req,
UseGuards,
} from '@nestjs/common';
import { RoomService } from './room.service';
import { ApiOperation, ApiResponse, ApiTags } from '@nestjs/swagger';
import { Request } from 'express';
import User from '../entities/user.entity';
import { SessionAuthGuard } from '../auth/auth.guard';

@Controller('room')
@ApiTags('room')
@UseGuards(SessionAuthGuard)
export class RoomController {
private readonly logger = new Logger(RoomController.name);

Expand Down
82 changes: 24 additions & 58 deletions server/src/room/room.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ import User from 'src/entities/user.entity';
import { RoomUserService } from 'src/roomUser/room.user.service';
import { UserService } from 'src/user/user.service';
import { Repository } from 'typeorm';
import * as util from 'util';
import RoomUser from '../entities/roomUser.entity';

@Injectable()
Expand All @@ -27,19 +26,7 @@ export class RoomService {
private readonly roomRepository: Repository<Room>,
) {}

async createRoom(userSession: User) {
const { provider, providerId } = userSession;

const user = await this.userService.findUserByProviderInfoWithRooms({
provider,
providerId,
});

if (!user) {
throw new InternalServerErrorException('유저를 찾을 수 없습니다.');
}
if (user.joinedRooms && user.joinedRooms.length > 0)
throw new BadRequestException('이미 방에 참가 중입니다.');
async createRoom(user: User) {
if (user.username == null)
throw new BadRequestException('username이 없습니다.');

Expand All @@ -50,8 +37,8 @@ export class RoomService {
host: user,
})
.save();
await this.roomUserService.createOrRestoreRoomUser({ room, user });

await this.roomUserService.create({ room, user });
return room;
}

Expand All @@ -62,35 +49,23 @@ export class RoomService {
return hash.substring(0, 6).toUpperCase();
}

async joinRoom(userSession: User, roomCode: string) {
const { provider, providerId } = userSession;

const user = await this.userService.findUserByProviderInfo({
provider,
providerId,
});
if (!user) throw new BadRequestException('존재하지 않는 유저입니다.');

const roomUser = await this.roomUserService.findRoomUserByUser(user);
async joinRoom(user: User, roomCode: string) {
const joinedRooms = this.findJoinedRooms(user);

if (roomUser) {
if (joinedRooms != null) {
throw new BadRequestException('이미 참가한 방이 있습니다.');
}

const roomUsers = await this.roomUserRepository.find({
where: { room: { code: roomCode } },
});
const roomUsers =
await this.roomUserService.findRoomUsersByRoomCode(roomCode);

if (roomUsers.length === 0) {
throw new BadRequestException('존재하지 않는 방입니다.');
}

const room = roomUsers[0].room;

if (room == null) {
throw new InternalServerErrorException('방을 찾을 수 없습니다.');
}

this.logger.debug(`user ${user.username} joining room ${room.code}...`);
return this.roomUserRepository.create({ room, user }).save();
}
Expand All @@ -100,24 +75,19 @@ export class RoomService {
return await this.roomRepository.remove(room);
}

async exitRoom(userSession: User) {
const { provider, providerId } = userSession;

const user = await this.userService.findUserByProviderInfoWithRooms({
provider,
providerId,
});
if (!user) throw new BadRequestException('존재하지 않는 유저입니다.');

this.logger.debug('user from db:', util.inspect(user));

if (!user.joinedRooms || user.joinedRooms.length === 0)
throw new BadRequestException('참가 중인 방이 없습니다.');
async exitRoom(user: User) {
const joinedRooms = await user.joinedRooms;
if (joinedRooms == null) {
throw new InternalServerErrorException(
'참가 중인 방을 찾을 수 없습니다.',
);
}

if (user.joinedRooms.length > 1)
if (joinedRooms.length > 1)
throw new InternalServerErrorException('참가 중인 방이 여러 개입니다.');

const roomUser = user.joinedRooms[0];
const roomUser = joinedRooms[0];

await this.roomUserRepository.remove(roomUser);

const room = roomUser.room;
Expand All @@ -134,18 +104,14 @@ export class RoomService {
}
}

async findRoomParticipating(user: User) {
const roomUser = await this.roomUserService.findRoomUserByUser(user);
if (!roomUser) {
this.logger.warn(
`user ${user.username} is not participating in any room!`,
async findJoinedRooms(user: User) {
const joinedRooms = await user.joinedRooms;
if (joinedRooms == null) {
throw new InternalServerErrorException(
'참가 중인 방을 찾을 수 없습니다.',
);
return null;
}
return this.roomRepository.findOne({
where: {
joinedUsers: { id: roomUser.id },
},
});

return joinedRooms;
}
}
8 changes: 7 additions & 1 deletion server/src/roomUser/room.user.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ export class RoomUserService {
private readonly roomUserRepository: Repository<RoomUser>,
) {}

async createOrRestoreRoomUser(roomUserInput: RoomUserInput) {
async create(roomUserInput: RoomUserInput) {
return this.roomUserRepository.create(roomUserInput).save();
}

Expand All @@ -26,4 +26,10 @@ export class RoomUserService {
where: { user: { id: user.id } },
});
}

async findRoomUsersByRoomCode(roomCode: string) {
return this.roomUserRepository.find({
where: { room: { code: roomCode } },
});
}
}

0 comments on commit ef3489b

Please sign in to comment.