這一年欠的技術債都快還完了,真的是可喜可賀
剛好最近忙完手上的事情就來處理 GraphQL
然後順便練習多用一點英文
GraphQL 的官網介紹蠻詳細的,這篇先做個基本的練習
後面再處理有關認證或資料庫的搭配
GraphQL 是一種 API 的查詢語言,使用在數據定義及查詢
GraphQL 不依賴於任何 storage engine 或任何 database,可以想像成專門為『溝通』而產生的 interface
使用 GraphQL 對比 RESTful API 的好處在於
$ mkdir YourProject
$ cd YourProject
$ code .
$ touch main.go
$ go mod init
Important:Tutorial not wroted this step
:$ go get github.com/99designs/gqlgen
$ go run github.com/99designs/gqlgen init
graph/schema.graphqls
type Link {
id: ID!
title: String!
address: String!
user: User!
}
type User {
id: ID!
name: String!
}
type Query {
links: [Link!]!
}
input NewLink {
title: String!
address: String!
}
input RefreshTokenInput{
token: String!
}
input NewUser {
username: String!
password: String!
}
input Login {
username: String!
password: String!
}
type Mutation {
createLink(input: NewLink!): Link!
createUser(input: NewUser!): String!
login(input: Login!): String!
# we'll talk about this in authentication section
refreshToken(input: RefreshTokenInput!): String!
}
go run github.com/99designs/gqlgen generate
Step 5 失敗的話嘗試 $ go get github.com/99designs/gqlgen
如果正常執行的話會出現
validation failed: packages.Load: /Users/liujinhua/go/src/Go-GraphQL/graph/schema.resolvers.go:53:72: undefined: model.NewTodo
/Users/liujinhua/go/src/Go-GraphQL/graph/schema.resolvers.go:53:89: undefined: model.Todo
/Users/liujinhua/go/src/Go-GraphQL/graph/schema.resolvers.go:56:62: undefined: model.Todo
在把沒有使用到的 function 刪除即可
a query in graphql is asking for data, you use a query and specify what you want and graphql will return it back to you.
schema.resolvers.go
的 Linksfunc (r *queryResolver) Links(ctx context.Context) ([]*model.Link, error) {
var links []*model.Link
dummyLink := model.Link{
Title: "our dummy link",
Address: "https://address.org",
User: &model.User{Name: "admin"},
}
links = append(links, &dummyLink)
return links, nil
}
$ go run server.go
http://localhost:8080
,或用 Postman 請求 GraphQLSimply mutations are just like queries but they can cause a data write, Technically Queries can be used to write data too however it’s not suggested to use it. So mutations are like queries, they have names, parameters and they can return data.
schema.resolvers.go
的 CreateLinkfunc (r *mutationResolver) CreateLink(ctx context.Context, input model.NewLink) (*model.Link, error) {
var link model.Link
var user model.User
link.Address = input.Address
link.Title = input.Title
user.Name = "test"
link.User = &user
return &link, nil
}
$ go run server.go
http://localhost:8080
,或用 Postman 請求 GraphQL