Skip to content

Conversation

@twalla26
Copy link
Collaborator

@twalla26 twalla26 commented Dec 3, 2024

Note

  • 작성자: 송수민
  • 작성 날짜: 2024.12.04

✅ 체크리스트

  • 코드가 정상적으로 작동하는지 확인했습니다.
  • 주요 변경사항에 대한 설명을 작성했습니다.
  • 코드 스타일 가이드에 따라 코드를 작성했습니다.

🧩 작업 내용

  • 모든 API 응답에 적절한 상태 코드 반환
    • 로그인이 필요한 API에 401 상태 코드 반환
    • internal server error의 경우 500 상태 코드 반환
  • 로그인 유무에 따라 적절한 응답 반환
    • isScrap: boolean
      • 전체 질문지 조회
      • 카테고리별 질문지 조회
      • 질문지 상세 페이지
    • scrapCount: boolean
      • 질문지 상세 페이지
    • 로그인하지 않은 유저는 모두 false 반환
  • 질문지 작성자 관련 에러 fix

📝 작업 상세 내역

모든 API 응답에 적절한 상태 코드 반환

  • 기존에는 응답의 성공 유무와 관계없이 200이나 201 상태 코드를 반환했었습니다.
  • 상태 코드를 정확하게 반환해달라는 정우님의 요청으로 모든 API 요청이 적절한 상태 코드를 반환할 수 있도록 수정했습니다.
@Get("my")
@UseGuards(AuthGuard("jwt"))
@UsePipes(new ValidationPipe({ transform: true }))
async getMyQuestionLists(
    @Res() res,
    @Query() query: PaginateQueryDto,
    @JwtPayload() token: IJwtPayload
) {
    try {
        const userId = token ? token.userId : null;

        if (!userId)
            return res.status(HttpStatus.UNAUTHORIZED).json({ // 401 반환
                success: false,
                message: "Login required.",
            });

        const { myQuestionLists, meta } = await this.questionListService.getMyQuestionLists(
            userId,
            query
        );
        return res.status(HttpStatus.OK).json({ // 200 반환
            success: true,
            message: "My question lists received successfully.",
            data: {
                myQuestionLists,
                meta,
            },
        });
    } catch (error) {
        return res.status(HttpStatus.INTERNAL_SERVER_ERROR).json({ // 500 반환
            success: false,
            message: "Failed to get my question lists.",
            error: error.message,
        });
    }
}

로그인 유무에 따라 적절한 응답 반환

  • 찬우님께서 인증 가드를 수정해주신 덕분에 로그인 유무에 따라 적절한 응답을 반환할 수 있게 되었습니다.
  • 그와 관련된 isScrap, scrapCount 데이터를 반환할 수 있도록 구현했습니다.
  • 아래의 서비스 로직에서 userId가 null인지의 여부(로그인 여부)에 따라 데이터를 true, false로 반환해주고 있습니다.
async getQuestionListContents(questionListId: number, userId: number) {
    const questionList = await this.questionListRepository.findOne({
        where: { id: questionListId },
    });

    const { id, title, usage, isPublic } = questionList;
    const authorId = questionList.userId;

    if (!isPublic) {
        if (!userId || questionList.userId !== userId) {
            throw new Error("This is a private question list.");
        }
    }

    const contents = await this.questionRepository.getContentsByQuestionListId(questionListId);

    const categoryNames =
        await this.categoryRepository.findCategoryNamesByQuestionListId(questionListId);

    const author = await this.userRepository.getUserByUserId(authorId);
    const username = author.username;

    const isScrap = userId
        ? await this.questionListRepository.isQuestionListScrapped(id, userId)
        : false;

    const scrapCount = await this.questionListRepository.getScrapCount(id);

    const questionListContents: QuestionListContentsDto = {
        id,
        title,
        contents,
        categoryNames,
        usage,
        username,
        isScrap,
        scrapCount: parseInt(scrapCount.count),
    };

    return questionListContents;
}

질문지 작성자 관련 에러 fix

  • 질문지 상세 페이지에서 작성자를 의미하는 username에 나의 username을 반환하는 에러가 있었습니다.
  • 이를 질문지 작성자의 username을 반환하도록 수정했습니다.

📌 테스트 및 검증 결과

  • 로그인한 사용자가 받은 질문지 상세 페이지 응답
    image

💬 다음 작업 또는 논의 사항

  • 남은 문서화

@twalla26 twalla26 added 🐛 Bug Fix 해충 제거 🎁 Refactoring 리팩토링 labels Dec 3, 2024
@twalla26 twalla26 self-assigned this Dec 3, 2024
Copy link
Member

@yiseungyun yiseungyun left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

고수.의향이 가득.나네요. 본받고싶어요. 👍👍👍

수고 많으셨습니다!

Copy link
Collaborator

@blu3fishez blu3fishez left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

수고하셨습니당! 다 좋은데 만약에 혹시라도 하시면서 노가다하는 느낌이 드셨으면 모듈화가 필요하신거라고 생각합니다

Comment on lines +56 to +59
const isScrap = userId
? await this.questionListRepository.isQuestionListScrapped(id, userId)
: false;

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

타입 지정할 때 userId?: number 하시면 안받을수도 받을 수도 있습니당!@!

Comment on lines -432 to +550
return {
return res.status(HttpStatus.OK).json({
success: true,
message: "Question list unscrapped successfully.",
};
});
} else {
return {
return res.status(HttpStatus.INTERNAL_SERVER_ERROR).json({
success: false,
message: "Failed to unscrap question list.",
};
});
}
} catch (error) {
return {
return res.status(HttpStatus.INTERNAL_SERVER_ERROR).json({
success: false,
message: "Failed to unscrap question list.",
error: error.message,
};
});
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

모두 똑같은 방식으로 노가다 힘드셨을 것 같습니다..

노가다..? 노가다..? 어...? 반복되는걸 어떻게 해봐야할지 생각해보시면 좋을 것 같습니다~

Copy link
Member

@ShipFriend0516 ShipFriend0516 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

이 내용을 적용해야겠네요 고생하셧씁니다

Comment on lines +152 to +153
isScrap,
scrapCount: parseInt(scrapCount.count),
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

좋습니당

Comment on lines +237 to +241
return res.status(HttpStatus.UNAUTHORIZED).json({
success: false,
message: "Login required.",
});

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

오 이제 401에러로 잘 나오나요?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

넴 맞습니당~!

@twalla26 twalla26 merged commit 494aaa4 into boostcampwm-2024:dev Dec 4, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

🐛 Bug Fix 해충 제거 🎁 Refactoring 리팩토링

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants