Skip to content

Commit

Permalink
Merge pull request #100 from boostcampwm2023/feat/96-diary-delete-res…
Browse files Browse the repository at this point in the history
…ponse-handling

[Feat] 일기 삭제 API에 대한 서버 응답 수정 및 e2e 테스트 작성
  • Loading branch information
JoonSoo-Kim authored Nov 22, 2023
2 parents 8687241 + e6a9164 commit 77176d1
Show file tree
Hide file tree
Showing 7 changed files with 108 additions and 14 deletions.
4 changes: 2 additions & 2 deletions BE/src/auth/auth.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { JwtModule } from "@nestjs/jwt";
import { PassportModule } from "@nestjs/passport";
import { JwtStrategy } from "./jwt.strategy";
import { UsersModule } from "src/users/users.module";
import { IdGuard } from "./guard/auth.id-guard";
import { PrivateDiaryGuard } from "./guard/auth.diary-guard";

@Module({
imports: [
Expand All @@ -20,7 +20,7 @@ import { IdGuard } from "./guard/auth.id-guard";
UsersModule,
],
controllers: [AuthController],
providers: [AuthService, JwtStrategy, IdGuard],
providers: [AuthService, JwtStrategy, PrivateDiaryGuard],
exports: [PassportModule],
})
export class AuthModule {}
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { AuthGuard } from "@nestjs/passport";
import { DiariesRepository } from "src/diaries/diaries.repository";

@Injectable()
export class IdGuard extends AuthGuard("jwt") {
export class PrivateDiaryGuard extends AuthGuard("jwt") {
constructor(private readonly diariesRepository: DiariesRepository) {
super();
}
Expand All @@ -30,7 +30,7 @@ export class IdGuard extends AuthGuard("jwt") {
if (this.getUserId(request.user) === requestDiary.user.userId) {
return true;
} else {
throw new NotFoundException();
throw new NotFoundException("존재하지 않는 일기입니다.");
}
}

Expand Down
14 changes: 8 additions & 6 deletions BE/src/diaries/diaries.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import {
} from "./diaries.dto";
import { Diary } from "./diaries.entity";
import { AuthGuard } from "@nestjs/passport";
import { IdGuard } from "src/auth/guard/auth.id-guard";
import { PrivateDiaryGuard } from "src/auth/guard/auth.diary-guard";
import { GetUser } from "src/auth/get-user.decorator";
import { User } from "src/users/users.entity";

Expand All @@ -39,7 +39,7 @@ export class DiariesController {
}

@Get("/:uuid")
@UseGuards(IdGuard)
@UseGuards(PrivateDiaryGuard)
async readDiary(@Param("uuid") uuid: string): Promise<Object> {
const readDiaryDto: ReadDiaryDto = { uuid };
const diary = await this.diariesService.readDiary(readDiaryDto);
Expand Down Expand Up @@ -105,15 +105,17 @@ export class DiariesController {
}

@Put()
@UseGuards(IdGuard)
@UseGuards(PrivateDiaryGuard)
modifyDiary(@Body() updateDiaryDto: UpdateDiaryDto): Promise<Diary> {
return this.diariesService.modifyDiary(updateDiaryDto);
}

@Delete("/:uuid")
@UseGuards(IdGuard)
deleteBoard(@Param("uuid") uuid: string): Promise<void> {
@UseGuards(PrivateDiaryGuard)
@HttpCode(204)
async deleteDiary(@Param("uuid") uuid: string): Promise<void> {
const deleteDiaryDto: DeleteDiaryDto = { uuid };
return this.diariesService.deleteDiary(deleteDiaryDto);
await this.diariesService.deleteDiary(deleteDiaryDto);
return;
}
}
2 changes: 1 addition & 1 deletion BE/src/diaries/diaries.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ export class UpdateDiaryDto {
}

export class DeleteDiaryDto {
@IsUUID()
@IsUUID("4", { message: "일기 uuid 값이 uuid 양식이어야 합니다." })
uuid: string;
}

Expand Down
2 changes: 1 addition & 1 deletion BE/src/diaries/diaries.repository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ export class DiariesRepository {
async getDiaryByUuid(uuid: string): Promise<Diary> {
const found = await Diary.findOneBy({ uuid });
if (!found) {
throw new NotFoundException(`Can't find Diary with uuid: [${uuid}]`);
throw new NotFoundException(`존재하지 않는 일기입니다.`);
}
return found;
}
Expand Down
5 changes: 3 additions & 2 deletions BE/src/diaries/diaries.service.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Injectable } from "@nestjs/common";
import { Injectable, NotFoundException } from "@nestjs/common";
import { DiariesRepository } from "./diaries.repository";
import { Diary } from "./diaries.entity";
import {
Expand Down Expand Up @@ -68,6 +68,7 @@ export class DiariesService {
}

async deleteDiary(deleteDiaryDto: DeleteDiaryDto): Promise<void> {
return this.diariesRepository.deleteDiary(deleteDiaryDto);
await this.diariesRepository.deleteDiary(deleteDiaryDto);
return;
}
}
91 changes: 91 additions & 0 deletions BE/test/diaries.delete.e2e-spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
import { Test, TestingModule } from "@nestjs/testing";
import { INestApplication } from "@nestjs/common";
import * as request from "supertest";
import { AppModule } from "../src/app.module";
import { ValidationPipe } from "@nestjs/common";

describe("AppController (e2e)", () => {
let app: INestApplication;
let accessToken: string;
let diaryUuid: string;

beforeEach(async () => {
const moduleFixture: TestingModule = await Test.createTestingModule({
imports: [AppModule],
}).compile();

app = moduleFixture.createNestApplication();
app.enableCors();
app.useGlobalPipes(new ValidationPipe());

await app.init();

const signInPost = await request(app.getHttpServer())
.post("/auth/signin")
.send({
userId: "commonUser",
password: process.env.COMMON_USER_PASS,
});

accessToken = signInPost.body.accessToken;

const createDiaryPost = await request(app.getHttpServer())
.post("/diaries")
.set("Authorization", `Bearer ${accessToken}`)
.send({
title: "title",
content: "this is content.",
point: "1.5,5.5,10.55",
date: "2023-11-14",
tags: ["tagTest", "tagTest2"],
shapeUuid: "0c99bbc6-e404-464b-a310-5bf0fa0f0fa7",
});

diaryUuid = createDiaryPost.body.uuid;
console.log(diaryUuid);
});

afterEach(async () => {
await app.close();
});

it("정상 요청 시 200 OK 응답", async () => {
const postResponse = await request(app.getHttpServer())
.delete(`/diaries/${diaryUuid}`)
.set("Authorization", `Bearer ${accessToken}`)
.expect(204);
});

it("액세스 토큰 없이 요청 시 401 Unauthorized 응답", async () => {
const postResponse = await request(app.getHttpServer())
.delete(`/diaries/${diaryUuid}`)
.expect(401);

const body = JSON.parse(postResponse.text);

expect(body.message).toBe("Unauthorized");
});

it("존재하지 않는 일기에 대한 요청 시 404 Not Found 응답", async () => {
const postResponse = await request(app.getHttpServer())
.delete(`/diaries/5d4a854d-cd2d-46a8-8adc-acec0270e4dc`)
.set("Authorization", `Bearer ${accessToken}`)
.expect(404);

const body = JSON.parse(postResponse.text);

expect(body.message).toContain("존재하지 않는 일기입니다.");
});

// 유저 회원가입 및 로그인 후 글 생성하고 commonUser에서 해당 글에 대해 삭제 요청 보내기
// it("타인의 일기에 대한 요청 시 404 Not Found 응답", async () => {
// const postResponse = await request(app.getHttpServer())
// .delete(`/diaries/${diaryUuid}`)
// .set("Authorization", `Bearer ${accessToken}`)
// .expect(204);

// const body = JSON.parse(postResponse.text);

// expect(body.message).toContain("존재하지 않는 일기입니다.");
// });
});

0 comments on commit 77176d1

Please sign in to comment.