TypeScript와 Graphql을 사용하여 서버를 개발할 때 2가지의 방식 중 하나를 택하여 해당 클래스에 해당하는 graphql 스키마를 만들어줘야 한다.
Schema-first방식을 적용한다면 아래와 같은 Schema들을 직접 작성해주어야한다.
type Board {
number: Int!
writer: String!
title: String!
contents: String!
}
type ProductCategory {
id: String!
name: String!
}
type ProductSaleslocation {
id: String!
address: String!
addressDetail: String!
lat: Float!
lng: Float!
meetingTime: DateTime!
}
type User {
id: String!
email: String!
name: String!
age: Int!
point: Int!
}
type Product {
id: String!
name: String!
description: String!
price: Int!
isSoldout: Boolean!
productCategory: ProductCategory!
user: User!
productSaleslocation: ProductSaleslocation!
productTags: [ProductTag!]!
}
type ProductTag {
id: String!
name: String!
products: [Product!]!
}
다음은 Code-first방식을 적용한 코드이다.
@ObjectType()
export class ProductTag {
@Field(() => String)
id: string;
@Field(() => String)
name: string;
@Field(() => [Product])
products: Product[];
}
ObjectType()을 선언해주어 Entity임을 Graphql에게 알려준다. 이후에 내부의 값들은 Field()로 선언하여 각각의 변수들이 어떠한 타입의 값을 갖는지 알려준다. 참고로 TypeScript에서는 정수를 'number'타입으로 작성하지만 Graphql은 'Int'타입으로 적어줘야한다.
위와 같이 내가 코드를 작성해주면 Graphql은 아래와 같이 스키마를 만든다.
type ProductTag {
id: String!
name: String!
products: [Product!]!
}