반업주부의 일상 배움사
[Golang] 단숨에 GraphQL 적용하기 [gqlgen] 본문
반응형
새로운 폴더 만들고 시작할께요.
1. 설치
$ go mod init banjubu
$ go get github.com/99designs/gqlgen
$ printf '// +build tools\npackage tools\nimport _ "github.com/99designs/gqlgen"' | gofmt > tools.go
$ go run github.com/99designs/gqlgen init
$ go run server.go
2. graph/resolver.go
package graph
import "banjubu/graph/model"
// This file will not be regenerated automatically.
//
// It serves as dependency injection for your app, add any dependencies you require here.
type Resolver struct {
id int
todos []*model.Todo
}
3. graph/schema.resolvers.go
package graph
// This file will be automatically regenerated based on the schema, any resolver implementations
// will be copied through when generating and any unknown code will be moved to the end.
import (
"banjubu/graph/generated"
"banjubu/graph/model"
"context"
"fmt"
)
func (r *mutationResolver) CreateTodo(ctx context.Context, input model.NewTodo) (*model.Todo, error) {
r.id++
todo := &model.Todo{
Text: input.Text,
ID: fmt.Sprintf("T%d", r.id),
User: &model.User{ID: input.UserID, Name: "user " + input.UserID},
}
r.todos = append(r.todos, todo)
return todo, nil
}
func (r *queryResolver) Todos(ctx context.Context) ([]*model.Todo, error) {
return r.todos, nil
}
// Mutation returns generated.MutationResolver implementation.
func (r *Resolver) Mutation() generated.MutationResolver { return &mutationResolver{r} }
// Query returns generated.QueryResolver implementation.
func (r *Resolver) Query() generated.QueryResolver { return &queryResolver{r} }
type mutationResolver struct{ *Resolver }
type queryResolver struct{ *Resolver }
4. 확인 - http://localhost:8080 접속
5. Todo 추가
mutation {
createTodo(input:{
text: "first todo"
userId: "user1"
}) {
id
text
done
user {
id
name
}
}
}
6. Todo 리스트 확인
{
todos {
id
text
done
user {
id
name
}
}
}
7. 스키마 변경 > 제너레이팅
$ go run github.com/99designs/gqlgen generate --verbose
영어, 중국어 공부중이신가요?
홈스쿨 교재. 한 권으로 가족 모두 할 수 있어요!
반응형
LIST
'IT 인터넷 > Golang' 카테고리의 다른 글
[Copper] 카퍼 소개 (0) | 2022.09.15 |
---|---|
[Golang] Gin + gqlgen [GraphQL] (0) | 2022.05.19 |
[Golang] Supervisor로 데몬 실행하기 (0) | 2022.05.18 |
[Golang] AWS CloudFront > 무효화 (CreateInvalidation) (0) | 2022.05.18 |
[Golang] 파일 업로드 > S3 (0) | 2022.05.18 |
Comments