1.要有go.mod和go.sum這兩個文件才能去執行go run github.com/99designs/gqlgen去更新generated.go和models_gen.go,在沒有這兩個文件的時候去執行該命令,會把generated.go文件刪除
2.要執行了go mod init github.com/[username]/[project]才能生成go.mod
3.要執行了go get github.com/99designs/gqlgen才能生成go.sum
4.在generated.go裏面存放了很多信息,但我們常用到的是interface接口信息,如:
type MutationResolver interface {
CreateTodo(ctx context.Context, input NewTodo) (*Todo, error)
}
在resolver.go裏面去編寫這些接口的實現,也就是增刪改查的業務邏輯,如:
func (r *mutationResolver) CreateTodo(ctx context.Context, input NewTodo) (*Todo, error) {
newID := r.nextID
r.nextID++
newTodo := &Todo{
DatabaseID: newID,
Description: input.Text,
}
r.todos = append(r.todos, newTodo)
return newTodo, nil
}
5.gqlgen.yml的schema屬性是指明schema.graphql存放的位置
schema: "*.graphql"
6.gqlgen.yml的exec.filename屬性是指明generated.go存放的位置
exec:
filename: generated.go
7.gqlgen.yml的model.filename屬性是指明model_gen.go存放的位置
model:
filename: models_gen.go
8.schema和struct有的字段名稱可能是不匹配的,但傳的值還是一樣的,只是傳給struct的時候改了個名稱,不是直接用schema的名稱,這個問題可以在gqlgen.yml裏面配置解決
models:
#用於schema和struct的字段的不同名稱的匹配
Todo: # Object
fields:
text:
fieldName: Description # Field
schema裏面的text字段,傳給struct時變成了Description
9.models_gen.go和generated.go是用go run github.com/99designs/gqlgen生成的,不用編輯
10.Resolver結構體一般包含的屬性是要操作的其他結構體
11.在server.go使用NewExecutableSchema(cfg Config),可以做數據的初始化,如:
func New() Config {
c := Config{
Resolvers: &Resolver{
todos: []*Todo{
{DatabaseID: 1, Description: "A todo not to forget", Done: false},
{DatabaseID: 2, Description: "This is the most important", Done: false},
{DatabaseID: 3, Description: "Please do this or else", Done: false},
},
nextID: 3,
},
}
return c
}
type Resolver struct {
todos []*Todo
nextID int
}
12.使用了@goModel指令後,該schema無法通過命令更新到gen.go中,所以它的struct只能自定義編寫,如:
type User
@goModel(model:"github.com/99designs/gqlgen/example/config.User") {
id: ID!
goo:String!
name: String! @goField(name:"FullName")
}
其實這個功能也能夠在gqlgen.yml裏面實現,如
models:
User:
model: github.com/99designs/gqlgen/example/config.User
13.input是輸入類型,一般作爲Mutation函數的參數傳遞,如:
input NewTodo {
text: String!
userId: String!
foo:String!
}
type Mutation {
createTodo(input: NewTodo!): Todo!
}