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


repository.go
package bookimport("context""log""graphql/infrastructure""go.mongodb.org/mongo-driver/bson""go.mongodb.org/mongo-driver/mongo/options")funcGetBookByName(ctxcontext.Context, name string) (result interface{}){var book Bookdata :=infrastructure.Mongodb.Collection("booklist").FindOne(ctx,bson.M{"name": name})data.Decode(&book)return book}funcGetBookList(ctxcontext.Context, limit int) (result interface{}){var book Bookvar books []Bookoption := options.Find().SetLimit(int64(limit))cur, err:= infrastructure.Mongodb.Collection("booklist").Find(ctx, bson.M{},option)defer cur.Close(ctx)if err != nil {log.Println(err)return nil}for cur.Next(ctx) {cur.Decode(&book)books = append(books, book)}return books}funcInsertBook(ctxcontext.Context, book Book) error {_, err :=infrastructure.Mongodb.Collection("booklist").InsertOne(ctx, book)return err}funcUpdateBook(ctxcontext.Context, book Book) 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)return err}funcDeleteBook(ctxcontext.Context, name string) error {_, err :=infrastructure.Mongodb.Collection("booklist").DeleteOne(ctx,bson.M{"name": name})return err}
response.go
package bookimport("encoding/json""net/http""time")type SetResponsestruct {Statusstring`json:"status"`Datainterface{} `json:"data,omitempty"`AccessTime string`json:"accessTime"`}funcHttpResponseSuccess(w http.ResponseWriter, r *http.Request, data interface{}){setResponse := SetResponse{Status:http.StatusText(200),AccessTime: time.Now().Format("02-01-2006 15:04:05"),Data:data}response, _ :=json.Marshal(setResponse)w.Header().Set("Content-Type", "Application/json")w.WriteHeader(200)w.Write(response)}funcHttpResponseError(w http.ResponseWriter, r *http.Request, data interface{},code int) {setResponse := SetResponse{Status:http.StatusText(code),AccessTime: time.Now().Format("02-01-2006 15:04:05"),Data:data}response, _ :=json.Marshal(setResponse)w.Header().Set("Content-Type", "Application/json")w.WriteHeader(code)w.Write(response)}
routes.go
package bookimport("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)return r}
最后 , 创建名为 main.go的文件 。
main.go
package mainimport("github.com/go-chi/chi""graphql/book""graphql/infrastructure""log""net/http""net/url")funcmain() {routes := chi.NewRouter()r := book.RegisterRoutes(routes)log.Println("Server ready at 8080")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|Facebook:如何在Golang中搭建GraphQL?


推荐阅读