总体上来说,GraphQL是前端给后端加活,对后端来说这个好处不是那么显而易见,尤其是规模不是那么大的情况下。如果前段后端是同一个人做的话,GraphQL会更容易被大家接受。
以下例子是简单尝试了下效果,实际项目中应该只会在数据网关+NodeJS服务里使用GraphQL,其他则还是会使用REST风格。
- go mod定义:
module demo-service
go 1.16
require (
github.com/gin-gonic/gin v1.7.1
github.com/graph-gophers/graphql-go v1.1.0
)
- router:
r.Any("/graphql", graphql.GraphqlCtl)
- GraphqlCtl.go:
package graphql
import (
"context"
"github.com/gin-gonic/gin"
"github.com/graph-gophers/graphql-go"
)
type ClientQuery struct {
OpName string `json:"opName"`
Query string `json:"query"`
Variables map[string]interface{} `json:"variables"`
}
func GraphqlCtl(c *gin.Context) {
basicParam := config.GetBasicParammeter(c)
basicParam.Log.Info("GraphqlCtrl Start")
args := &ClientQuery{}
if err := c.Bind(args); err != nil {
c.Error(err)
basicParam.Log.Warnw("bind args error", "parameters", map[string]interface{}{"error": err.Error()})
c.JSON(400, gin.H{"error": err.Error()})
return
}
Schema, err := graphql.ParseSchema(schema.Schema, &resolver.RootResolver{})
if err != nil {
c.Error(err)
basicParam.Log.Warnw("ParseSchema error", "parameters", map[string]interface{}{"error": err.Error()})
c.JSON(500, gin.H{"error": err.Error()})
return
}
ctx := context.WithValue(c.Request.Context(), "ginContext", c)
resp := Schema.Exec(ctx, args.Query, args.OpName, args.Variables)
c.JSON(200, resp)
}
- schema定义:
package schema
var Schema = `
schema {
query: Query
mutation: Mutation
}
type Account {
accountCode: String!
accountID: ID!
accountName: String!
email: String!
mobile: String!
}
type Tenant {
tenantID: String!
tenantCode: String!
tenantName: String!
email: String!
mobile: String!
parentTenantCode: String!
parentTenantID: String!
}
type Query {
accountByID(accountID: ID!): Account!
accountByName(accountName: String!): [Account!]!
tenantByCode(tenantCode: String!): Tenant!
}
type Mutation {
}
`
- account.go:
type RootResolver struct{}
type AccountResolver struct{ u dao.Account }
func getGinContextFromContext(ctx context.Context) (*gin.Context, error) {
ginContext := ctx.Value("ginContext")
if ginContext == nil {
err := fmt.Errorf("could not retrieve gin.Context")
return nil, err
}
c, ok := ginContext.(*gin.Context)
if !ok {
err := fmt.Errorf("gin.Context has wrong type")
return nil, err
}
return c, nil
}
func (r *RootResolver) AccountByID(ctx context.Context, args struct{ AccountID graphql.ID }) (*AccountResolver, error) {
c, err := getGinContextFromContext(ctx)
if err != nil {
return nil, err
}
basicParam := config.GetBasicParammeter(c)
basicParam.SetDB()
accountInfo, err := dao.GetByID(string(args.AccountID), basicParam) //get date from DB
if err != nil {
return nil, fmt.Errorf("get account info error:%v", err)
}
return &AccountResolver{*accountInfo}, nil
}
func (r *RootResolver) AccountByName(ctx context.Context, args struct{ AccountName string }) ([]*AccountResolver, error) {
c, err := getGinContextFromContext(ctx)
if err != nil {
return nil, err
}
basicParam := config.GetBasicParammeter(c)
basicParam.SetDB()
accountList, err := dao.GetByAccountName(args.AccountName, basicParam) //get date from DB
if err != nil {
return nil, fmt.Errorf("get account by name error:%v", err)
}
result := []*AccountResolver{}
for _, v := range *accountList {
result = append(result, &AccountResolver{v})
}
return result, nil
}
func (r *AccountResolver) AccountID() graphql.ID {
return graphql.ID(r.u.AccountId.String)
}
func (r *AccountResolver) AccountCode() string {
return r.u.AccountCode.String
}
func (r *AccountResolver) AccountName() string {
return r.u.AccountName.String
}
func (r *AccountResolver) Email() string {
return r.u.Email.String
}
func (r *AccountResolver) Mobile() string {
return r.u.Mobile.String
}
- tenant.go
type TenantResolver struct{ u dao.Tenant }
func (r *RootResolver) TenantByCode(ctx context.Context, args struct{ TenantCode string }) (*TenantResolver, error) {
c, err := getGinContextFromContext(ctx)
if err != nil {
return nil, err
}
basicParam := config.GetBasicParammeter(c)
basicParam.SetDB()
tenantInfo, err := dao.GetByTenantCode(args.TenantCode, basicParam) //get date from DB
if err != nil {
return nil, fmt.Errorf("get tenant info error:%v", err)
}
return &TenantResolver{*tenantInfo}, nil
}
func (r *RootResolver) Tenants(ctx context.Context, args struct{ ParentTenantCode string }) ([]*TenantResolver, error) {
c, err := getGinContextFromContext(ctx)
if err != nil {
return nil, err
}
basicParam := config.GetBasicParammeter(c)
basicParam.SetDB()
list, err := dao.GetByParentTenantCode(args.ParentTenantCode, basicParam) //get date from DB
if err != nil {
return nil, fmt.Errorf("get tenant by name error:%v", err)
}
result := []*TenantResolver{}
for _, v := range *list {
result = append(result, &TenantResolver{v})
}
return result, nil
}
func (r *TenantResolver) TenantID() string {
return r.u.TenantId.String
}
func (r *TenantResolver) TenantCode() string {
return r.u.TenantCode.String
}
func (r *TenantResolver) TenantName() string {
return r.u.TenantName.String
}
func (r *TenantResolver) Email() string {
return r.u.Email.String
}
func (r *TenantResolver) Mobile() string {
return r.u.Mobile.String
}
func (r *TenantResolver) ParentTenantCode() string {
return r.u.ParentTenantCode.String
}
func (r *TenantResolver) ParentTenantID() string {
return r.u.ParentTenantId.String
}
- 测试例:
- 入参:
{
"opName": "Account",
"query": "query Account($accountName: String!) { accountByName(accountName: $accountName) {accountID \n accountName \n mobile}}",
"variables": {
"accountName":"tom",
"accountID":"1",
"tenantCode":"cat"
}
}
- 返回例:
{
"data": {
"accountByName": [
{
"accountID": "1",
"accountName": "TEOM",
"mobile": "+861860000000"
}
]
}
}
- 入参:
{
"opName": "Account",
"query": "query Account($accountName: String!, $tenantCode: String!) { tenantByCode(tenantCode: $tenantCode) {tenantID \n tenantName \n mobile} \n accountByName(accountName: $accountName) {accountID \n accountName \n mobile}}",
"variables": {
"accountName":"tom",
"accountID":"1",
"tenantCode":"cat"
}
}
- 返回例:
{
"data": {
"tenantByCode": {
"tenantID": "1",
"tenantName": "cat",
"mobile": "123213213213"
},
"accountByName": [
{
"accountID": "tom",
"accountName": "1",
"mobile": "+861860000000"
}
]
}
}
网友评论