在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
设计API参数列表 type User { id: ID email: String! post(id: ID!): Post posts: [Post!]! follower(id: ID!): User followers: [User!]! followee(id: ID!): User followees: [User!]! }type Post { id: ID user: User! title: String! body: String! comment(id: ID!): Comment comments: [Comment!]! } type Comment { id: ID user: User! post: Post! title: String body: String! }
转换为go的实现(User为例)
API查询 graphql设计模式有三种查询类型
query和mutation设计如下: type Query { user(id: ID!): User } type Mutation { createUser(email: String!): User removeUser(id: ID!): Boolean follow(follower: ID!, followee: ID!): Boolean unfollow(follower: ID!, followee: ID!): Boolean createPost(user: ID!, title: String!, body: String!): Post removePost(id: ID!): Boolean createComment(user: ID!, post: ID!, title: String!, body: String!): Comment removeComment(id: ID!): Boolean } 转换为go的实现 var QueryType = graphql.NewObject(graphql.ObjectConfig{ Name: "Query", Fields: graphql.Fields{ "user": &graphql.Field{ Type: UserType, Args: graphql.FieldConfigArgument{ "id": &graphql.ArgumentConfig{ Description: "User ID", Type: graphql.NewNonNull(graphql.ID), }, }, Resolve: func(p graphql.ResolveParams) (interface{}, error) { i := p.Args["id"].(string) id, err := strconv.Atoi(i) if err != nil { return nil, err } return GetUserByID(id) }, }, }, })var MutationType = graphql.NewObject(graphql.ObjectConfig{ Name: "Mutation", Fields: graphql.Fields{ "createUser": &graphql.Field{ Type: UserType, Args: graphql.FieldConfigArgument{ "email": &graphql.ArgumentConfig{ Description: "New User Email", Type: graphql.NewNonNull(graphql.String), }, }, Resolve: func(p graphql.ResolveParams) (interface{}, error) { email := p.Args["email"].(string) user := &User{ Email: email, } err := InsertUser(user) return user, err }, }, "removeUser": &graphql.Field{ Type: graphql.Boolean, Args: graphql.FieldConfigArgument{ "id": &graphql.ArgumentConfig{ Description: "User ID to remove", Type: graphql.NewNonNull(graphql.ID), }, }, Resolve: func(p graphql.ResolveParams) (interface{}, error) { i := p.Args["id"].(string) id, err := strconv.Atoi(i) if err != nil { return nil, err } err = RemoveUserByID(id) return (err == nil), err }, }, }, }) 接口的启用也很简单 func main() { schema, err := graphql.NewSchema(graphql.SchemaConfig{ Query: QueryType, Mutation: MutationType, }) if err != nil { log.Fatal(err) } http.Handle("/graphql", handler(schema)) log.Fatal(http.ListenAndServe("0.0.0.0:8080", nil)) }func handler(schema graphql.Schema) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { query, err := ioutil.ReadAll(r.Body) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } result := graphql.Do(graphql.Params{ Schema: schema, RequestString: string(query), }) w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK) json.NewEncoder(w).Encode(result) } } 请求实例 |
请发表评论