열거형
TypeGraphQL은 @EnumType 데코레이터를 통해 타입스크립트의 enum을 GraphQL EnumType으로 정의할 수 있습니다.
1. TS에서 enum 정의하기
먼저 TypeScript에서 열거형을 정의합니다.
//
// implicit value 0, 1, 2, 3
enum CounterCommand {
UP, // 0
DOWN, // 1
}
//
// or explicit values
enum CounterCommand {
UP = "up",
DOWN = "down",
}2. 열거형 등록
registerEnumType를 사용하여 열거형을 등록합니다.
import { registerEnumType } from "type-graphql";
registerEnumType(CounterCommand, {
name: "CounterCommand",
description: "카운터 명령어", // optional
});위의 코드의 결과로 다음 ddl이 생성됩니다.
enum CounterCommand {
UP
DOWN
}3. 열거형 사용하기
이후로는 열거형을 일반 타입처럼 사용할 수 있습니다.
@Resolver()
class CounterResolver {
private cnt: number = 0;
@Mutation(() => Int)
// v
count(@Arg("command", () => CounterCommand) command: CounterCommand) {
switch (command) {
case CounterCommand.UP: {
this.cnt++;
break;
}
case CounterCommand.DOWN: {
this.cnt--;
break;
}
default: {
throw new Error(`Unknown command : ${command}`);
}
}
return this.cnt;
}
}쿼리에서는 다음 형태로 열거형에 접근할 수 있습니다.
query {
count(command: UP)
}예제 다운로드
이 포스팅에 사용된 전체 코드는 여기에서 확인할 수 있습니다.
'# GraphQL > TypeGraphQL' 카테고리의 다른 글
| [TypeGraphQL] 상속, Inheritance (0) | 2020.07.04 |
|---|---|
| [TypeGraphQL] Scalar (0) | 2020.06.14 |
| [TypeGraphQL] @InputType, @ArgsType (0) | 2020.06.13 |
| [TypeGraphQL] 기본 자료형과 @ObjectType (0) | 2020.06.08 |
| ApolloServer + TypeScript + TypeGraphQL 조합으로 GraphQL 서버 시작하기 (0) | 2020.06.07 |