原创

Go集成GraphQL

温馨提示:
本文最后更新于 2020年07月09日,已超过 1,610 天没有更新。若文章内的图片失效(无法正常加载),请留言反馈或直接联系我

初始化环境,下载依赖

# 使用go mod管理依赖
go mod init 项目名称

# 获取gqlgen依赖
go get github.com/99designs/gqlgen

创建 main 方法

我创建了一个 main 方法demo2-main.go

package main

import "github.com/99designs/gqlgen/cmd"

/*
go run demo2-main.go init
 */
func main() {
    cmd.Execute()
}

初始化 gqlgen

然后直接在此 main 方法的目录下执行:

go run demo2-main.go init

之后就会生成这些文件:

Go-GraphQL-demo2.png

文件说明:

├── go.mod
├── go.sum
├── gqlgen.yml               - The gqlgen config file, knobs for controlling the generated code.
├── graph
│   ├── generated            - A package that only contains the generated runtime
│   │   └── generated.go
│   ├── model                - A package for all your graph models, generated or otherwise
│   │   └── models_gen.go
│   ├── resolver.go          - The root graph resolver type. This file wont get regenerated
│   ├── schema.graphqls      - Some schema. You can split the schema into as many graphql files as you like
│   └── schema.resolvers.go  - the resolver implementation for schema.graphql
└── server.go                - The entry point to your app. Customize it however you see fit

创建自己的schema.graphqls

上面那些是 init 之后自动生成的,所以需要创建我自己的。

my-graphql-01.png

# pojo
type Student {
  id: ID!
  name: String!
  sex: String
  age: Int
  birthDate: String
  provinceCity: String
}

input NewStudent {
  id: ID!
  name: String!
  sex: String
  age: Int
  birthDate: String
  provinceCity: String
}

# 插入
type Mutation {
  createStudent(input: NewStudent!): Student!
}

# 查询
type Query {
  students: [Student!]!
}

重写model_gen.go

my-graphql-02.png

// Code generated by github.com/99designs/gqlgen, DO NOT EDIT.

package model

type NewStudent struct {
    ID           string  `json:"id"`
    Name         string  `json:"name"`
    Sex          *string `json:"sex"`
    Age          *int    `json:"age"`
    BirthDate    *string `json:"birthDate"`
    ProvinceCity *string `json:"provinceCity"`
}

type Student struct {
    ID           string  `json:"id"`
    Name         string  `json:"name"`
    Sex          *string `json:"sex"`
    Age          *int    `json:"age"`
    BirthDate    *string `json:"birthDate"`
    ProvinceCity *string `json:"provinceCity"`
}

重写resolver.go

my-graphql-03.png

package graph

import "study-golang/gqlgen/demo2/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{}

type Resolver struct{
    students []*model.Student
}

重新初始化

完成这些操作之后,初始化我们自定义的 schema,执行:

go run demo2-main.go init

然后会发现 generated 文件夹下的generated.go被重新初始化为我们自定义的 schema 的类型的了,不仅如此,所有的 schema 类型都从 todo 修改为我定义的 schema 类型了。

my-graphql-04.png

写自己的 Crud 逻辑

为了演示,这里简便一点,只写了插入和查询的操作:

my-graphql-05.png

func (r *mutationResolver) CreateStudent(ctx context.Context, input model.NewStudent) (*model.Student, error) {
    //panic(fmt.Errorf("not implemented"))
    student := &model.Student{
        ID: input.ID,
        Name: input.Name,
        Sex: input.Sex,
        Age: input.Age,
        BirthDate: input.BirthDate,
        ProvinceCity: input.ProvinceCity,
    }
    r.students = append(r.students, student)
    return student, nil
}

func (r *queryResolver) Students(ctx context.Context) ([]*model.Student, error) {
    //panic(fmt.Errorf("not implemented"))
    return r.students, nil
}

启动server.go

最后启动server.go,访问:http://localhost:8080

插入操作

createStudent

gqlgen -createStudent-01.png

完整的:

gqlgen -createStudent-02.png

逗号其实也可以不加~

# 执行插入操作
mutation createStudent {
  createStudent(input:{
    id:3,
    name:"lzhpo03",
    sex:"男",
    age:1,
    birthDate:"2019-06-16",
    provinceCity:"江西赣州"}
  )
  {
    id
    name
    sex
    age
    birthDate
    provinceCity
  }
}

我插入 3 条测试数据,然后在下面查询。

查询操作

gqlgen -findStudents-01.png

# 执行查询操作,需要什么字段,就写什么字段,前提是字段有的情况下
query findStudents {
  students {
    id
    name
    sex
    age
    birthDate
    provinceCity
  }
}
本文目录