반업주부의 일상 배움사

[Golang] Gin + gqlgen [GraphQL] 본문

IT 인터넷/Golang

[Golang] Gin + gqlgen [GraphQL]

Banjubu 2022. 5. 19. 13:42
반응형

 

새로운 폴더 만들고 시작할께요.

 

1. 설치

$ go mod init banjubu
$ go get github.com/gin-gonic/gin
$ 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
$ rm -rf server.go

 

2. main.go

package main

import (
	"banjubu/graph"
	"banjubu/graph/generated"

	"github.com/99designs/gqlgen/graphql/handler"
	"github.com/99designs/gqlgen/graphql/playground"
	"github.com/gin-gonic/gin"
)

func graphqlHandler() gin.HandlerFunc {
	h := handler.NewDefaultServer(generated.NewExecutableSchema(generated.Config{Resolvers: &graph.Resolver{}}))

	return func(c *gin.Context) {
		h.ServeHTTP(c.Writer, c.Request)
	}
}

func playgroundHandler() gin.HandlerFunc {
	h := playground.Handler("GraphQL", "/query")

	return func(c *gin.Context) {
		h.ServeHTTP(c.Writer, c.Request)
	}
}

func main() {
	r := gin.Default()
	r.POST("/query", graphqlHandler())
	r.GET("/", playgroundHandler())
	r.Run(":3000")
}

 

3. 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
}

 

4. 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 }

 

 

5. 확인 - http://localhost:3000 접속

 

6. Todo 추가

mutation {
  createTodo(input:{
    text: "first todo"
    userId: "user1"
  }) {
    id
    text
    done
    user {
      id
      name
    }
  }
}

 

7. Todo 리스트 확인

{
  todos {
    id
    text
    done
    user {
      id
      name
    }
  }
}

 

 

8. 스키마 변경 > 제너레이팅

$ go run github.com/99designs/gqlgen generate --verbose

 

 

 

영어, 중국어 공부중이신가요?

홈스쿨 교재. 한 권으로 가족 모두 할 수 있어요!

 

한GLO 미네르바에듀 : 네이버쇼핑 스마트스토어

한글로 영어가 된다?! 한글로[한GLO]는 영어 중국어 일어 러시아어 스페인어가 됩니다!!

smartstore.naver.com

 

 

반응형
LIST
Comments