Skip to content

Commit

Permalink
Merge pull request #8 from mju-likelion/feature/users-api
Browse files Browse the repository at this point in the history
  • Loading branch information
kMinsAlgorithm authored Aug 9, 2023
2 parents 72cf470 + f22c6d4 commit 2e7d7c6
Show file tree
Hide file tree
Showing 8 changed files with 96 additions and 39 deletions.
17 changes: 17 additions & 0 deletions prisma/migrations/20230726073815_/migration.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
/*
Warnings:
- You are about to drop the column `userName` on the `User` table. All the data in the column will be lost.
- A unique constraint covering the columns `[username]` on the table `User` will be added. If there are existing duplicate values, this will fail.
- Added the required column `username` to the `User` table without a default value. This is not possible if the table is not empty.
*/
-- DropIndex
DROP INDEX "User_userName_key";

-- AlterTable
ALTER TABLE "User" DROP COLUMN "userName",
ADD COLUMN "username" TEXT NOT NULL;

-- CreateIndex
CREATE UNIQUE INDEX "User_username_key" ON "User"("username");
14 changes: 3 additions & 11 deletions prisma/schema.prisma
Original file line number Diff line number Diff line change
@@ -1,6 +1,3 @@
// This is your Prisma schema file,
// learn more about it in the docs: https://pris.ly/d/prisma-schema

generator client {
provider = "prisma-client-js"
}
Expand All @@ -12,29 +9,24 @@ datasource db {
shadowDatabaseUrl = env("SHADOW_DATABASE_URL")
}

// 여기에 모델들 정의하시면 됩니다.

// 정의 완료 후 'yarn prisma migrate dev' 명령 입력하셔서 migrate 진행하시면 됩니다.
model Room {
code String @id
dates String[]
dateOnly Boolean
startTime String?
endTime String?
users User[]
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
dates String[]
users User[]
}

model User {
id String @id @default(uuid())
username String @unique
password String
enableTimes String[]
room Room @relation(fields: [roomId], references: [code])
roomId String
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
room Room @relation(fields: [roomId], references: [code])
}

// 위의 코드에서 Room 모델에서 users 필드가 추가되었으며, User 모델에서는 room 필드를 옵셔널한 관계로 수정하였습니다.
2 changes: 1 addition & 1 deletion src/api/auth/jwt.strategy.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { ExtractJwt, Strategy } from 'passport-jwt';
import { PassportStrategy } from '@nestjs/passport';
import { Inject, Injectable, UnauthorizedException } from '@nestjs/common';
import { Inject, Injectable } from '@nestjs/common';
import authConfig from 'src/config/authConfig';
import { ConfigType } from '@nestjs/config';

Expand Down
4 changes: 2 additions & 2 deletions src/api/users/dto/create-appointment.dto.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Transform } from 'class-transformer';
import { IsBoolean, IsOptional, IsString, Matches } from 'class-validator';
import { IsBoolean, IsOptional, IsString } from 'class-validator';

export class CreateAppointmentDto {
@IsString()
Expand All @@ -10,7 +10,7 @@ export class CreateAppointmentDto {

@Transform(({ value }) => value.trim())
@IsString()
@Matches(/^[A-Za-z0-9!@#$%^&*()]{8,30}$/)
// @Matches(/^[A-Za-z0-9!@#$%^&*()]{8,30}$/)
password: string;

@IsOptional()
Expand Down
4 changes: 1 addition & 3 deletions src/api/users/dto/get-user-name.dto.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
import { Transform } from 'class-transformer';
import { IsBoolean, IsOptional, IsString, Matches } from 'class-validator';
import { PartialType } from '@nestjs/mapped-types';
import { IsString } from 'class-validator';

export class GetUserNameDto {
@IsString()
Expand Down
14 changes: 13 additions & 1 deletion src/api/users/dto/update-user.dto.ts
Original file line number Diff line number Diff line change
@@ -1 +1,13 @@
export class UpdateUserDto {}
import { IsBoolean, IsOptional, IsString } from 'class-validator';

export class UpdateUserDto {
@IsString()
username: string;

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

@IsString({ each: true })
dates: string[];
}
13 changes: 7 additions & 6 deletions src/api/users/users.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@ import {
Controller,
Post,
Body,
Req,
Patch,
UseGuards,
Param,
Get,
Query,

Check warning on line 9 in src/api/users/users.controller.ts

View workflow job for this annotation

GitHub Actions / CI

'Query' is defined but never used
} from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';

Expand All @@ -19,7 +19,6 @@ import { GetUserNameDto } from './dto/get-user-name.dto';
export class UsersController {
constructor(private readonly usersService: UsersService) {}

// 예약 가능 시간 한번에 넘기는걸로, 응답에 JWT도 들어가야함.
@Post()
create(@Body() createAppointmentDto: CreateAppointmentDto) {
return this.usersService.createAppointment(createAppointmentDto);
Expand All @@ -30,10 +29,12 @@ export class UsersController {
return this.usersService.findOne(username);
}

// header에 JWT 넘어와야함
@UseGuards(AuthGuard('jwt'))
@Patch()
update(@Req() req, @Body() updateUserDto: UpdateUserDto) {
return this.usersService.update(req.userId, updateUserDto);
@Patch(':roomCode')
update(
@Param('roomCode') roomCode: string,
@Body() updateUserDto: UpdateUserDto
) {
return this.usersService.update(roomCode, updateUserDto);
}
}
67 changes: 52 additions & 15 deletions src/api/users/users.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,26 @@ export class UsersService {
private readonly roomService: RoomsService,
private authService: AuthService
) {}

private async isDateOnlyFormatValid(dateOnly: boolean, dates: string[]) {
let result = true;
if (!dateOnly) {
for (const date of dates) {
const [_, selectedTime] = date.split(' ');

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

View workflow job for this annotation

GitHub Actions / CI

'_' is assigned a value but never used
if (!selectedTime) {
result = false;
}
}
}
return result;
}

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

async createAppointment(createAppointmentDto: CreateAppointmentDto) {
const badRequestErros = [];
const notFoundErros = [];
Expand All @@ -38,14 +58,8 @@ export class UsersService {
dates는 ['2023-07-19 12:30','2023-07-20 13:45']이런 식으로 된 배열이며
공백을 기준으로 날짜와 시간으로 나눕니다.
*/
if (!dateOnly) {
for (const date of dates) {
const [_, selectedTime] = date.split(' ');
if (!selectedTime) {
badRequestErros.push('Time must be selected when dateOnly is false');
break;
}
}
if (!(await this.isDateOnlyFormatValid(dateOnly, dates))) {
badRequestErros.push('Time must be provided when dateOnly is false');
}

const sortedDates = dates.sort();
Expand All @@ -56,7 +70,7 @@ export class UsersService {
if (badRequestErros.length > 0) {
throw new BadRequestException(badRequestErros);
}

console.log(roomCode);
if (!(await this.roomService.findOne(roomCode))) {
notFoundErros.push('Room does not exist');
}
Expand Down Expand Up @@ -84,13 +98,36 @@ export class UsersService {
return token;
}

findOne(username: string): Promise<User> {
return this.prismaService.user.findUnique({
async update(roomCode: string, updateUserDto: UpdateUserDto) {
const badRequestErros = [];
const notFoundErros = [];
const { username, dates, dateOnly } = updateUserDto;
const userInfo = await this.findOne(username);

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

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

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

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

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

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

update(id: string, updateUserDto: UpdateUserDto) {
return `This action updates a #${id} user`;
}
}

0 comments on commit 2e7d7c6

Please sign in to comment.