아래 공식문서를 참고하여 작성했습니다
Resolvers
How Apollo Server processes GraphQL operations
www.apollographql.com
Documentation | NestJS - A progressive Node.js framework
Nest is a framework for building efficient, scalable Node.js server-side applications. It uses progressive JavaScript, is built with TypeScript and combines elements of OOP (Object Oriented Progamming), FP (Functional Programming), and FRP (Functional Reac
docs.nestjs.com
1. 타입 확인
스키마를 보면 타입이 Order, Product 두개가 있으며 Product에 orderList로 Order가 포함되는걸 볼 수 있습니다.
type Order {
id: ID!
shopName: String!
date: DateTime!
productId: Float!
content: String!
cost: Float!
}
type Product {
id: ID!
name: String!
price: Float!
stock: Float!
orderList: [Order!]!
}
2. 요청시 쿼리문 예상
- id가 1인 product의 id, name과 productId가 1인 order들을 전부 모아서 orderList로 가져옵니다
query {
product(id:1){
id
name
orderList{
id
shopName
}
}
}
3. ProductResolver에서 문제 해결
-> '@ResolveField'로 문제를 해결합니다
1. 과정 2번에서 product 쿼리를 했으니 getProduct 메서드가 실행되고 id가 일치하는 product를 찾아서 리턴됩니다.
2. orderList를 찾아오는걸 @ResolveField 데코레이터가 붙은 getOrders에서 처리합니다.
3. 파라미터로 @Parent를 받는데 getProduct의 결과값이 여기로 넘겨받습니다.
4. product의 아이디를 가지고 order안에 있는 productId와 비교해서 찾아옵니다.
5. 1번과 4번에서 받은걸 합쳐서 응답해줍니다.
@Resolver(() => Product)
export class ProductResolver {
constructor(
private productService: ProductService,
private orderService: OrderService,
) {}
@Mutation(() => Product)
async createProduct(@Args('productInput') productInput: ProductInput) {
return await this.productService.createProduct(productInput);
}
@Query(() => Product, { name: 'product' })
async getProduct(@Args('id', { type: () => ID }) id: number) {
return await this.productService.getProduct(id);
}
@ResolveField('orderList', () => [Order])
async getOrders(@Parent() product: Product) {
const { id } = product;
const result = await this.orderService.getOrderByProduct(id);
return result;
}
}
4. Playground에서 확인
-id가 1인 product와 order-productId가 1인 orderList를 응답합니다.
GraphQL 적응하기가 참 어려운데 이부분이 처음에는 관계적으로 이해하는게 어려웠습니다ㅠㅠ
REST API를 만들땐 백엔드 맘대로 만들고 그 방식대로 요청하는 느낌이였는데 GraphQL은 그 반대더라구요.
Playground에서 요청하는걸 먼저 생각하고 뒷편에서 어떻게 요청에 응답하는 순서가 맞는 것 같아요...
아직 모르는게 많지만 계속 알아가면서 포스팅을 이어가보겠습니다!

'BackEnd > GraphQL' 카테고리의 다른 글
[GraphQL] NestJS 프로젝트에 적용하기 1 (Query, Mutation) (0) | 2022.11.06 |
---|