Skip to content

Commit

Permalink
Merge pull request #11 from mju-likelion/feature/fix-users-service
Browse files Browse the repository at this point in the history
users service 관련 이런저런 수정
  • Loading branch information
ndaemy authored Aug 9, 2023
2 parents 0a63894 + 7bc0778 commit 83dc0d3
Show file tree
Hide file tree
Showing 8 changed files with 48 additions and 80 deletions.
17 changes: 0 additions & 17 deletions prisma/migrations/20230726073815_/migration.sql

This file was deleted.

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
-- CreateTable
CREATE TABLE "Room" (
"code" TEXT NOT NULL,
"dates" TEXT NOT NULL,
"dateOnly" BOOLEAN NOT NULL,
"startTime" TEXT,
"endTime" TEXT,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
"dates" TEXT[],

CONSTRAINT "Room_pkey" PRIMARY KEY ("code")
);
Expand All @@ -24,8 +24,5 @@ CREATE TABLE "User" (
CONSTRAINT "User_pkey" PRIMARY KEY ("id")
);

-- CreateIndex
CREATE UNIQUE INDEX "User_username_key" ON "User"("username");

-- AddForeignKey
ALTER TABLE "User" ADD CONSTRAINT "User_roomId_fkey" FOREIGN KEY ("roomId") REFERENCES "Room"("code") ON DELETE RESTRICT ON UPDATE CASCADE;
2 changes: 1 addition & 1 deletion prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ model Room {

model User {
id String @id @default(uuid())
username String @unique
username String
password String
enableTimes String[]
roomId String
Expand Down
3 changes: 2 additions & 1 deletion src/api/auth/auth.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,8 @@ export class AuthService {
}

async validateUser(username: string, password: string) {
const user = await this.prismaService.user.findUnique({
// TODO: 임시땜빵 - 추후 room code 를 같이 받도록 수정해야 함
const user = await this.prismaService.user.findFirst({
where: { username },
});

Expand Down
4 changes: 0 additions & 4 deletions src/api/users/dto/create-appointment.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,6 @@ export class CreateAppointmentDto {
// @Matches(/^[A-Za-z0-9!@#$%^&*()]{8,30}$/)
password: string;

@IsOptional()
@IsBoolean()
dateOnly?: boolean;

@IsString({ each: true })
dates: string[];
}
5 changes: 0 additions & 5 deletions src/api/users/users.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,6 @@ export class UsersController {
return this.usersService.createAppointment(createAppointmentDto);
}

@Get(':username')
findOne(@Param() { username }: GetUserNameDto) {
return this.usersService.findOne(username);
}

@UseGuards(AuthGuard('jwt'))
@Patch(':roomCode')
update(
Expand Down
83 changes: 44 additions & 39 deletions src/api/users/users.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import {
NotFoundException,
} from '@nestjs/common';
import { hash } from 'bcrypt';
import { User } from '@prisma/client';
import { Room, User } from '@prisma/client';

Check warning on line 7 in src/api/users/users.service.ts

View workflow job for this annotation

GitHub Actions / CI

'User' is defined but never used

import { PrismaService } from '@/prisma/prisma.service';

Expand All @@ -25,7 +25,7 @@ export class UsersService {
let result = true;
if (!dateOnly) {
for (const date of dates) {
const [_, selectedTime] = date.split(' ');
const [, selectedTime] = date.split(' ');
if (!selectedTime) {
result = false;
}
Expand All @@ -34,48 +34,49 @@ export class UsersService {
return result;
}

async findOne(username: string): Promise<User> {
return this.prismaService.user.findUnique({
where: { username },
});
}

async createAppointment(createAppointmentDto: CreateAppointmentDto) {
const badRequestErros = [];
const notFoundErros = [];
const { roomCode, username, password, dates, dateOnly } =
createAppointmentDto;
const badRequestErrors = [];
const notFoundErrors = [];
const { roomCode, username, password, dates } = createAppointmentDto;

const uniqueDates = new Set(dates);
if (dates.length !== uniqueDates.size) {
badRequestErros.push('dates must be unique');
badRequestErrors.push('dates must be unique');
}

const sortedDates = dates.sort();
if (dates.join(',') !== sortedDates.join(',')) {
badRequestErrors.push('dates must be sorted');
}

let room: Room;
try {
room = await this.roomService.findOne(roomCode);
} catch (e) {
if (e instanceof NotFoundException) {
notFoundErrors.push('Room does not exist');
}
}

const dateOnly = room.dateOnly;

/*
dates는 ['2023-07-19 12:30','2023-07-20 13:45']이런 식으로 된 배열이며
공백을 기준으로 날짜와 시간으로 나눕니다.
*/
if (!(await this.isDateOnlyFormatValid(dateOnly, dates))) {
badRequestErros.push('Time must be provided when dateOnly is false');
}

const sortedDates = dates.sort();
if (dates.join(',') !== sortedDates.join(',')) {
badRequestErros.push('dates must be sorted');
badRequestErrors.push('Time must be provided when dateOnly is false');
}

if (badRequestErros.length > 0) {
throw new BadRequestException(badRequestErros);
}
console.log(roomCode);
if (!(await this.roomService.findOne(roomCode))) {
notFoundErros.push('Room does not exist');
if (badRequestErrors.length > 0) {
throw new BadRequestException(badRequestErrors);
}

const hashedPassword = await hash(password, 10);
const token = this.authService.login(username, password);

if (notFoundErros.length > 0) {
throw new NotFoundException(notFoundErros);
if (notFoundErrors.length > 0) {
throw new NotFoundException(notFoundErrors);
}

try {
Expand All @@ -95,34 +96,38 @@ export class UsersService {
}

async update(roomCode: string, updateUserDto: UpdateUserDto) {
const badRequestErros = [];
const notFoundErros = [];
const badRequestErrors = [];
const notFoundErrors = [];
const { username, dates, dateOnly } = updateUserDto;
const userInfo = await this.findOne(username);
const userInfo = await this.prismaService.user.findFirst({
where: { username, roomId: roomCode },
});

if (!userInfo) {
badRequestErros.push('User does not exist');
badRequestErrors.push('User does not exist');
}

if (!(await this.roomService.findOne(roomCode))) {
notFoundErros.push('Room does not exist');
notFoundErrors.push('Room does not exist');
}

// 해당 유저가 수정한 가용시간에 대한 유효성을 검사한다.
if (!(await this.isDateOnlyFormatValid(dateOnly, dates))) {
badRequestErros.push('Time must be provided when dateOnly is false');
badRequestErrors.push('Time must be provided when dateOnly is false');
}

if (badRequestErros.length > 0) {
throw new BadRequestException(badRequestErros);
if (badRequestErrors.length > 0) {
throw new BadRequestException(badRequestErrors);
}

if (notFoundErros.length > 0) {
throw new NotFoundException(notFoundErros);
if (notFoundErrors.length > 0) {
throw new NotFoundException(notFoundErrors);
}

return await this.prismaService.user.update({
where: { username },
return this.prismaService.user.update({
where: {
id: userInfo.id,
},
data: { enableTimes: dates },
});
}
Expand Down

0 comments on commit 83dc0d3

Please sign in to comment.