Facebook|Facebook:如何在Golang中搭建GraphQL?( 三 )


package infrastructureimport("context""go.mongodb.org/mongo-driver/mongo""go.mongodb.org/mongo-driver/mongo/options""log")var Mongodb *mongo.Databasefunc(e *Environment) InitMongoDB()(db *mongo.Database, err error) {clientOptions :=options.Client().ApplyURI(e.Databases["mongodb"].Connection)client, err := mongo.Connect(context.TODO(),clientOptions)err = client.Ping(context.TODO(), nil)if err != nil {return db, err}Mongodb = client.Database(e.Databases["mongodb"].Name)log.Println("Mongodb Ready!!!")return db, err}
environmentConfiguration.go
package infrastructureimport("io/ioutil""log""os""path""runtime""gopkg.in/yaml.v2")func(env *Environment) SetEnvironment() {_, filename, _, _ := runtime.Caller(1)env.path = path.Join(path.Dir(filename),"environment/Connection.yml")_, err := os.Stat(env.path)if err != nil {panic(err)return}}func(env *Environment) LoadConfig() {content, err :=ioutil.ReadFile(env.path)if err != nil {log.Println(err)panic(err)}err =yaml.Unmarshal([]byte(string(content)), env)if err != nil {log.Println(err)panic(err)}if env.App.Debug == false {log.SetOutput(ioutil.Discard)}log.Println("Config load successfully!")return}
model.go
package infrastructuretypeapp struct{Appnamestring `yaml:"name"`Debugbool`yaml:"debug"`Portstring `yaml:"port"`Servicestring `yaml:"service"`Hoststring `yaml:"host"`}type database struct {Namestring `yaml:"name"`Connection string`yaml:"connection"`}type Environment struct {Appapp`yaml:"app"`Databases map[string]database`yaml:"databases"`pathstring}
第三 , 创建一个书目文件夹 , 创建如下文件:
Facebook|Facebook:如何在Golang中搭建GraphQL?
文章图片

文章图片

model.go
packagepackage booktypeBook struct {NamestringPricestringDescription string} booktypeBook struct {NamestringPricestringDescription string}
resolver.go
package bookimport("context""github.com/graphql-go/graphql")var productType = graphql.NewObject(graphql.ObjectConfig{Name: "Book",Fields: graphql.Fields{"name": &graphql.Field{Type: graphql.String,},"price":&graphql.Field{Type: graphql.String,},"description":&graphql.Field{Type: graphql.String,},},},)var queryType = graphql.NewObject(graphql.ObjectConfig{Name: "Query",Fields: graphql.Fields{"book":&graphql.Field{Type:productType,Description: "Get bookby name",Args: graphql.FieldConfigArgument{"name":&graphql.ArgumentConfig{Type: graphql.String,},},Resolve: func(pgraphql.ResolveParams) (interface{}, error) {var result interface{}name, ok :=p.Args["name"].(string)if ok {// Find productresult =GetBookByName(context.Background(), name)}return result, nil},},"list":&graphql.Field{Type:graphql.NewList(productType),Description: "Get booklist",Args: graphql.FieldConfigArgument{"limit":&graphql.ArgumentConfig{Type: graphql.Int,},},Resolve: func(paramsgraphql.ResolveParams) (interface{}, error) {var result interface{}limit, _ :=params.Args["limit"].(int)result =GetBookList(context.Background(), limit)return result, nil},},},})var mutationType =graphql.NewObject(graphql.ObjectConfig{Name: "Mutation",Fields: graphql.Fields{"create":&graphql.Field{Type:productType,Description: "Create newbook",Args: graphql.FieldConfigArgument{"name":&graphql.ArgumentConfig{Type:graphql.NewNonNull(graphql.String),},"price":&graphql.ArgumentConfig{Type:graphql.NewNonNull(graphql.String),},"description":&graphql.ArgumentConfig{Type:graphql.NewNonNull(graphql.String),},},Resolve: func(paramsgraphql.ResolveParams) (interface{}, error) {book := Book{Name:params.Args["name"].(string),Price:params.Args["price"].(string),Description:params.Args["description"].(string),}if err := InsertBook(context.Background(), book); err != nil {return nil, err}return book, nil},},"update":&graphql.Field{Type:productType,Description: "Update bookby name",Args: graphql.FieldConfigArgument{"name":&graphql.ArgumentConfig{Type:graphql.NewNonNull(graphql.String),},"price":&graphql.ArgumentConfig{Type: graphql.String,},"description":&graphql.ArgumentConfig{Type: graphql.String,},},Resolve: func(paramsgraphql.ResolveParams) (interface{}, error) {book := Book{}if name, nameOk := params.Args["name"].(string); nameOk {book.Name = name}if price, priceOk := params.Args["price"].(string); priceOk {book.Price = price}if description, descriptionOk :=params.Args["description"].(string); descriptionOk {book.Description = description}if err :=UpdateBook(context.Background(), book); err != nil {return nil, err}return book, nil},},"delete": &graphql.Field{Type:productType,Description: "Delete bookby name",Args: graphql.FieldConfigArgument{"name":&graphql.ArgumentConfig{Type:graphql.NewNonNull(graphql.String),},},Resolve: func(paramsgraphql.ResolveParams) (interface{}, error) {name, _ :=params.Args["name"].(string)if err := DeleteBook(context.Background(), name); err != nil {return nil, err}return name, nil},},},})// schemavar Schema, _ = graphql.NewSchema(graphql.SchemaConfig{Query:queryType,Mutation: mutationType,},)


推荐阅读