Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[NDD-79]: BE 재사용성 있는 코드 분리 && 활용성 확장 (1h / 1h) #21

Merged
merged 3 commits into from
Nov 8, 2023

Conversation

JangAJang
Copy link
Collaborator

@JangAJang JangAJang commented Nov 8, 2023

NDD-79 Powered by Pull Request Badge

Why

세 가지 이슈가 존재했다.

  1. AuthGuard를 통해 Member를 접근할 때 payload를 통한 id만을 조회한다.
    • 이로 인해, Controller에서 id만을 서비스로 보내고, 다시 리포지토리를 통해 Member객체를 받아와야 한다.
    • 이를 Guard에서 바로 Member를 반환하게 수정하는게 좋다고 생각했다.
  2. Util의 필요성이 존재했다.
    • request에서 header를 가져오는 로직이 생각보다 귀찮다.
      a. Authorization을 키로 헤더에서 문자열을 받아온다.
      b. 이를 'Bearer '를 제외한 나머지만을 가져온다.
      c. 해당 토큰을 활용한다.
    • 해당 부분을 함수 분리를 통해 적용하는게 좋다고 판단했다.
      • 비회원기능도 구현가능한 만큼, 모든 로직에서 Guard를 활용하지는 않는다(Guard 활용시, 토큰이 없으면 401에러를 바로 반환한다)
  3. Swagger option들이 장황하다.
@ApiProperty({
    example: 'CS/BE/FE/CUSTOM',
    description: '질문에 대한 카테고리',
  })

@ApiResponse({
    status: 204,
    description: '로그아웃 api, 회원의 토큰 정보를 db에서 삭제한다.',
  })

위의 로직들을 반복적으로 추가해야 한다.
문서를 위한 로직들이 프로덕션 코드와 같이 있는것이 불편했다.
이를 위해, 해당 내용이 간소화되게 리펙토링해야겠다는 계획이 생겼다.

How

@Injectable()
export class AccessTokenStrategy extends PassportStrategy(Strategy, 'jwt') {
  constructor(private memberRepository: MemberRepository) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      secretOrKey: process.env.JWT_SECRET,
    });
  }

  async validate(payload: TokenPayload) {
    const id = payload.id;
    return await this.memberRepository.findById(id);
  }
}

토큰을 통해서 최종적으로 Member객체를 가져오게 분리

export const getTokenValue = (request: Request) =>
  request.header('Authorization').split(' ').pop();

토큰 반환 로직을 바로 사용할 수 있게 분리

export const createPropertyOption = (example:unknown, description: string, type: Type): ApiPropertyOptions => {
    return {
        example : example,
        description: description,
        type: type,
    } as ApiPropertyOptions;
}

export const createApiResponseOption = (status:number, description:string, type: unknown) => {
    return {
        status: status,
        description: description,
        type: type,
    } as ApiResponseOptions;
}

옵션 생성을 함수로 처리할 수 있게 분리

Result

스크린샷 2023-11-08 16 40 00
req.user로 strategy에서 validate의 반환값을 가져온다.

스크린샷 2023-11-08 16 40 47
이전에 return한 req.user를 @useGuard(AuthGuard('jwt'))를 통해 활용할 수 있다.

@ApiResponse(createApiResponseOption(200, '테스트지롱', TokenResponse))
...
@ApiProperty(createPropertyOption('Bearer dlwkdgml', 'accessToken', String))

위의 코드처럼 create~~~Option을 통해 swagger의 json을 축약시킬 수 있다.

Prize

  • 코드 재사용성 강화
  • 문서화 코드로 인한 프로덕션 코드 가독성 저해 방지
  • Util을 통한 로직 간소화

Link

https://milk717.atlassian.net/browse/NDD-79

Co-authored-by: quiet-honey <skap0329@naver.com>
@JangAJang JangAJang added BE 백엔드 코드 변경사항 feature 새로운 기능이 추가 된 경우 labels Nov 8, 2023
Copy link
Collaborator

@quiet-honey quiet-honey left a comment

Choose a reason for hiding this comment

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

LGTM:)

@JangAJang JangAJang merged commit 4bf2972 into dev Nov 8, 2023
@delete-merged-branch delete-merged-branch bot deleted the feature/NDD-79 branch November 8, 2023 07:46
Yoon-Hae-Min pushed a commit that referenced this pull request Nov 11, 2023
* feat: Swagger에서 Property Option을 반복적으로 json으로 초기화하지 않게 생성 함수 구현

Co-authored-by: quiet-honey <skap0329@naver.com>

* feat: Swagger에서 Api Response의 json을 반복적으로 생성하지 않게 함수 기능 추가

Co-authored-by: quiet-honey <skap0329@naver.com>

* style: 사용되지 않는 import 제거

Co-authored-by: quiet-honey <skap0329@naver.com>

---------

Co-authored-by: quiet-honey <skap0329@naver.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
BE 백엔드 코드 변경사항 feature 새로운 기능이 추가 된 경우
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants