[오류일지] TypeORM과 Typescript를 이용하여 MySQL 정렬 기준 변수로 설정하기

Song·2021년 10월 25일
0

오류일지

목록 보기
3/5

현상

TypeORM과 Typescript를 이용하여 MySQL에서 데이터를 추출할 때 정렬 기준을 변수로 사용하려고 하니 아래와 같은 오류가 발생하였다.

  • dto.ts
// paginationInputDto.dto.ts
export class PaginationInputDto {
  @IsString()
  sort: string; // 'ASC: 오름차순, DESC: 내림차순' 
}
  • service.ts
const sort = paginationInputDto.sort;

// 쿼리문
const products = await this.productRepository.createQueryBuilder('product')   
      .orderBy("price", sort)	// 여기 sort에서 에러 발생
  • Error
Argument of type 'string' is not assignable to parameter of type '"ASC" | "DESC"'

원인

orderBy 에는 ASC 또는 DESC 만 가능하기에 'sort' 변수에도 이 두개의 단어외에는 다른 값들이 들어오지 못하도록 방지 해야하는데 그런 prevention 없이 string으로만 type을 정의해주니 마음에 안들었나보다.

해결

  • dto.ts
type sort = 'ASC' | 'DESC'; // typeorm 정렬

export class PaginationInputDto {
  @IsString()
  sort: sort; // 'ASC: 오름차순, DESC: 내림차순' 
}

type 을 이용하여 새로 정의한 후에 sort에 적용시킴으로서 해결하였다.

profile
Learn From Yesterday, Live Today, Hope for Tomorrow

0개의 댓글