[개발일지] 24.02.05 - TypeScript constructor 관련 러닝

김지호·2024년 2월 6일
0

개발일지

목록 보기
5/5
post-thumbnail

문제 상황


프론트에서 applier 들에 대한 세부정보를 불러오면 단순하게 applier 와 관련된 정보 뿐 아니라 applier의 계정정보가 모두 반환되는 사태가 발생하였다.

이를 해결 하기 위해 ShowApplierDto 클래스를 생성했다. 그러나 계속 password 정보가 나오는 것이었다.

해결방법


문제의 원인부터 말하자면 constructor의 인수를 private으로 선언했기 때문이었다.
문제의 코드

export class ShowApplierDto {
  businessId: string;
  companyName: string;
  ceoName: string;
  ...

  constructor(private applier: Applier) {
    this.businessId = applier.businessId;
    this.companyName = applier.companyName;
    this.ceoName = applier.ceoName;
	...
  }
}

이렇게 private을 먹이면 Controller에서 반환되는 ShowApplierDto에서 Applier 객체가 나온 후 쿼리 결과가 나오게 된다.

ShowApplierDto {
  applier: Applier {
    id: 2,
    businessId: '34-56-678901',
    password: '$2a$10$ZfH9z9k0Hph7svbEsZPAMufZt97zj1ZZqJYJaPEXJKtH0GXc2npBa',
    companyName: 'AA건설',
    ceoName: '김대표',
    companyAddress: '경기도 파주시 00로 xxx, 3층',
    ...
  },
  businessId: '34-56-678901',
  companyName: 'AA건설',
  ceoName: '김대표',
  companyAddress: '경기도 파주시 00로 xxx, 3층',
  ...
}

처음에는 저렇게 password가 나온 이유가 nestJS 라이프 사이클 상에서 Guard에서 반환되는 것이라 생각했다.

그러나 JSON을 뜯어보니 applier 객체가 불러져왔기 때문이었다.

단순하게 private을 지우니 applier가 나오지 않았다.

레슨런


우선 왜이러는지에 대해 알아보니...

TypeScript는 클래스의 constructor에서 Access Modifier(private, public, protected)를 사용한 매개변수는 자동으로 필드로 들어가게 된다.

그래서 private을 넣으면 response에 applier가 들어가게 된다!!

profile
문을 끝없이 두드리는 사람

0개의 댓글

관련 채용 정보