-
Golang GraphQL 서버 #5 (타입 리졸버 추가하기)Golang 2022. 3. 22. 12:28
https://zzihyeon.tistory.com/43
Golang GraphQL 서버 #4 (커스텀 타입 매핑하기)
https://zzihyeon.tistory.com/15 Golang GraphQL 서버 #3 zzihyeon.tistory.com/14 Golang graphQL Playground 사용법 zzihyeon.tistory.com/13 Golang GraphQL 서버 setting (gqlgen 사용) workspace directory..
zzihyeon.tistory.com
추가적으로 도움이 되는 기능
1. Type에 리졸버 추가하기
아래의 User struct에 대해서 school에 대한 Resolver를 추가하고 싶다면 어떻게 해야할까?
type User { uid: Int64! name: String! school: School } type School { uid: Int64! name: String! } type Query { user(uid: int64): User }
DB에 저장된 user 정보: { uid: 1, name: "zzihyeon", school: 1 }
보통 DB에 Data는 아래와 같이 school 타입이 아닌 school 을 가르키는 uid 값이 저장되어 있을 것이다. 이 때, User query를 요청할 때 선택에 따라 함께 school의 정보를 가져오고 싶다면 resolver를 추가해야 한다. 간단히 말하면 type을 요청할 때만 그 타입에 의존되어 불리는 함수라고 생각하면 될 것 같다.
EX) 만약 school field에 resolver function이 있다고 가정하면 위의 Query "user"를 호출했을 때
1. school field를 요청하지 않았을 때 school resolver function이 호출되지 않는다.
user(1){ uid name }
2. school field를 요청했을 때 school에 대한 정보를 가져오기 위한 resolver function이 호출된다.
user(1){ uid name school{ uid name } }
(graphql, resolver에 관한 글은 따로 정리해서 올리도록 하겠다.)
이전 글에서 query 혹은 Mutation으로 gqlgen을 했을 때 resolver가 생기는 것을 확인할 수 있었을 것이다. 그렇다면 field에 대한 resolver를 설정해보자.
# gqlgen.yml models: User: fields: school: resolver: true # force a resolver to be generated
위와 같이 gqlgen.yml의 User의 field에 school에 리졸버를 추가한 뒤 gqlgen으로 generate하면 schema.resolver.go에 새로운 리졸버 함수가 추가된 것을 확인할 수 있다. 이제 이 리졸버를 이용해서 school의 data를 가져올 수 있다.
여기까지 하면 기본적으로 golang에서 query, mutation setup을 하고 개발할 수 있다. subscription의 경우는 아직 어디에 사용할지 찾지 못해서 해보진 않았는데 만약 해보게 된다면 포스팅하도록 하겠다.
'Golang' 카테고리의 다른 글
Golang에서 SMTP 로 mail 보내기 (gmail) (0) 2022.09.04 Golang Server Base Code (graphQL, restAPI, mongoDB, postgresql) (0) 2022.04.22 Golang GraphQL 서버 #4 (커스텀 타입 매핑하기) (0) 2022.03.22 Golang Postgresql SQLC 설정하기 (0) 2022.03.21 golang postgresql migrate 설정하기 (0) 2022.03.21