golang+gin框架使用graphql-go
1、安装组件
go get github.com/graphql-go/graphql
go get github.com/graphql-go/handler
2、router(路由)里初始化
func init(){
AdminApiRouterGroup = Router.Group("/api/v1")
{
AdminApiRouterGroup.POST("/graphql", GraphqlHandler())
AdminApiRouterGroup.GET("/graphql", GraphqlHandler())
}
}
3、GraphqlHandler() 文件,新建一个router_graphql.go文件与router文件同目录,内容:
package router
import (
"c2matica.com/productcenter/graphql/schemas"
"github.com/gin-gonic/gin"
"github.com/graphql-go/graphql"
"github.com/graphql-go/handler"
)
var query = graphql.NewObject(graphql.ObjectConfig{
Name: "query",
Description: "query",
Fields: graphql.Fields{
"getList": &schemas.GetList,
},
})
var mutation = graphql.NewObject(graphql.ObjectConfig{
Name: "mutation",
Description: "mutation",
Fields: graphql.Fields{
"addProducts": &schemas.AddProducts,
},
})
var Schema, _ = graphql.NewSchema(graphql.SchemaConfig{
Query: query,
Mutation: mutation,
})
func GraphqlHandler() gin.HandlerFunc {
h := handler.New(&handler.Config{
Schema: &Schema,
Pretty: true,
GraphiQL: true,
})
return func(c *gin.Context) {
h.ContextHandler(c, c.Writer, c.Request)
}
}
4、在schemas创建product.go文件,写入接收参数和返回参数
package schemas
import (
"c2matica.com/productcenter/graphql/resolves"
"c2matica.com/productcenter/graphql/types"
"github.com/graphql-go/graphql"
)
var GetBomList = graphql.Field{
Name: "GetList",
Description: "GetList",
Type: types.GetListOutputType,
Args: graphql.FieldConfigArgument{
"name": &graphql.ArgumentConfig{
Type: graphql.String,
},
"after": &graphql.ArgumentConfig{
Type: graphql.Int,
},
"first": &graphql.ArgumentConfig{
Type: graphql.Int,
},
},
Resolve: resolves.GetListResolve,
}
5、GetListOutputType里的内容
package types
import (
"github.com/graphql-go/graphql"
)
var GetListOutputType= graphql.NewObject(graphql.ObjectConfig{
Name: "GetListOutputType",
Description: "GetListOutputType Model",
Fields: graphql.Fields{
"code": &graphql.Field{
Type: graphql.String,
},
"message": &graphql.Field{
Type: graphql.String,
},
"success": &graphql.Field{
Type: graphql.Boolean,
},
"output": &graphql.Field{
Type: InfoOutputType,
},
"edges": &graphql.Field{
Type: graphql.NewList(ListNodeType),
},
"totalCount": &graphql.Field{
Type: graphql.Int,
},
},
})
var InfoOutputType= graphql.NewObject(graphql.ObjectConfig{
Name: "InfoOutputType",
Description: "InfoOutputType Model",
Fields: graphql.Fields{
"id": &graphql.Field{
Type: graphql.Int,
},
},
})
var ListNodeType = graphql.NewObject(graphql.ObjectConfig{
Name: "ListNodeType ",
Description: "ListNodeType Model",
Fields: graphql.Fields{
"node": &graphql.Field{
Type: DetailType,
},
},
})
var DetailType= graphql.NewObject(graphql.ObjectConfig{
Name: "DetailType",
Description: "DetailType Model",
Fields: graphql.Fields{
"id": &graphql.Field{
Type: graphql.String,
},
},
})
6、在resolve文件夹里创建go文件,实现GetListResolve方法
func GetListResolve(p graphql.ResolveParams) (data interface{}, err error){
return
}