코드 개선을 통한 이해 (Nest)

손연주·2022년 4월 25일
1

Nestjs, typeScript, typeORM

위 스택들을 사용하며
본인이 작성한 코드의 일부분만 발췌했습니다.

Nest의 환경변수

...
import { env } from 'procees';
...

const url = `${env.IMPORT_BASE_URL}/vbanks/holder?bank_code=${bankCode}&bank_num=${bankAccountNumber}}`;
this.axiosInstance = ...

const { data }: any = await this.axiosInstance
	...
    .catch((error) => {
      if (error.response.status === 400) {
        throw new NotExistBankCodeException();
      } else if (error.response.status === 401) {
        throw new InvalidProviderTokenException();
      } else if (error.response.status === 404) {
        throw new InvalidBankAccountException();
      } else {
        throw new BaseException();
   	  }
     });
	...
}

변경 전 코드는 env를 import해왔지만
Nest 공식문서-환경변수를 참고하면 이를 지원해주는 서비스가 있다. 따라서 install -> import 후 모듈 연결을 해주고

const baseUrl = this.configService.get<string>('IMPORT_BASE_URL'); 

로 변경해주었고,

url을 mapper해주는 함수를 만들어서

export const urlMapper = (
  baseUrl: any,
  bankCode: string,
  bankAccountNumber: string,
) => {
  if (!baseUrl && !bankCode && !bankAccountNumber) {
	throw new ... // 에러 핸들링
  }

  return `${baseUrl}/vbanks/holder?bank_code=${bankCode}&bank_num=${bankAccountNumber}}`;
};

const url = urlMapper(baseUrl, bankCode, bankAccountNumber);

이런 식으로 작성했다.

  • urlMapper 함수는 다른 파일을 만들어(e.g.lib.ts) export해주었다.

또한 catch문에서 작성한 if문도 반복된 코드가 많기 때문에 swtich문으로 바꾸었다.

      .catch((error) => {
        const statusCode = error.response.status;

        switch (statusCode) {
          case 400:
            throw new NotExistBankCodeException();
          case 401:
            throw new InvalidProviderTokenException();
          case 404:
            throw new InvalidBankAccountException();
          default:
            throw new NeedPermissionException();
        }
      });
profile
할 수 있다는 생각이 정말 나를 할 수 있게 만들어준다.

0개의 댓글