读芯术|Facebook:如何在Golang中搭建GraphQL?( 四 )


repository.go
packagebookimport("context""log""graphql/infrastructure""go.mongodb.org/mongo-driver/bson""go.mongodb.org/mongo-driver/mongo/options")funcGetBookByName(ctxcontext.Context,namestring)(resultinterface{}){varbookBookdata:=infrastructure.Mongodb.Collection("booklist").FindOne(ctx,bson.M{"name":name})data.Decode(&book)returnbook}funcGetBookList(ctxcontext.Context,limitint)(resultinterface{}){varbookBookvarbooks[]Bookoption:=options.Find().SetLimit(int64(limit))cur,err:=infrastructure.Mongodb.Collection("booklist").Find(ctx,bson.M{},option)defercur.Close(ctx)iferr!=nil{log.Println(err)returnnil}forcur.Next(ctx){cur.Decode(&book)books=append(books,book)}returnbooks}funcInsertBook(ctxcontext.Context,bookBook)error{_,err:=infrastructure.Mongodb.Collection("booklist").InsertOne(ctx,book)returnerr}funcUpdateBook(ctxcontext.Context,bookBook)error{filter:=bson.M{"name":book.Name}update:=bson.M{"$set":book}upsertBool:=trueupdateOption:=options.UpdateOptions{Upsert:&upsertBool,}_,err:=infrastructure.Mongodb.Collection("booklist").UpdateOne(ctx,filter,update,&updateOption)returnerr}funcDeleteBook(ctxcontext.Context,namestring)error{_,err:=infrastructure.Mongodb.Collection("booklist").DeleteOne(ctx,bson.M{"name":name})returnerr}
response.go
packagebookimport("encoding/json""net/http""time")typeSetResponsestruct{Statusstring`json:"status"`Datainterface{}`json:"data,omitempty"`AccessTimestring`json:"accessTime"`}funcHttpResponseSuccess(whttp.ResponseWriter,r*http.Request,datainterface{}){setResponse:=SetResponse{Status:http.StatusText(200),AccessTime:time.Now().Format("02-01-200615:04:05"),Data:data}response,_:=json.Marshal(setResponse)w.Header().Set("Content-Type","Application/json")w.WriteHeader(200)w.Write(response)}funcHttpResponseError(whttp.ResponseWriter,r*http.Request,datainterface{},codeint){setResponse:=SetResponse{Status:http.StatusText(code),AccessTime:time.Now().Format("02-01-200615:04:05"),Data:data}response,_:=json.Marshal(setResponse)w.Header().Set("Content-Type","Application/json")w.WriteHeader(code)w.Write(response)}
routes.go
packagebookimport("github.com/go-chi/chi""github.com/go-chi/chi/middleware""github.com/graphql-go/handler")funcRegisterRoutes(r*chi.Mux)*chi.Mux{/*GraphQL*/graphQL:=handler.New(&handler.Config{Schema:&Schema,Pretty:true,GraphiQL:true,})r.Use(middleware.Logger)r.Handle("/query",graphQL)returnr}
最后 , 创建名为main.go的文件 。
main.go
packagemainimport("github.com/go-chi/chi""graphql/book""graphql/infrastructure""log""net/http""net/url")funcmain(){routes:=chi.NewRouter()r:=book.RegisterRoutes(routes)log.Println("Serverreadyat8080")log.Fatal(http.ListenAndServe(":8080",r))}funcinit(){val:=url.Values{}val.Add("parseTime","1")val.Add("loc","Asia/Jakarta")env:=infrastructure.Environment{}env.SetEnvironment()env.LoadConfig()env.InitMongoDB()}
运行程序的结果如下:
读芯术|Facebook:如何在Golang中搭建GraphQL?
文章图片
创建书目详情示例
GraphQL有很多优点 , 但事实证明 , 与RESTAPI相比 , GraphQL处理文件上传和简单API的性能表现有所不足 。 因此 , 我们必须首先了解要构建的系统 , 是否适合将GraphQL用作应用程序的设计架构 。


推荐阅读