问题
I'm trying to use both SuperGraph as-a-library and GqlGen.
So I have two handlers:
the first one is SuperGraph; this checks that it can carry out the operation
the second one is GqlGen; this checks that it can carry out the operation if the first one can't
The code I'm using is this:
type reqBody struct {
Query string `json:"query"`
}
func Handler(sg *core.SuperGraph, next http.Handler) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
bodyBytes, _ := ioutil.ReadAll(r.Body)
r.Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes))
var rBody reqBody
err = json.NewDecoder(bytes.NewBuffer(bodyBytes)).Decode(&rBody)
ctx := context.WithValue(r.Context(), core.UserIDKey, "user_id")
res, err := sg.GraphQL(ctx, rBody.Query, nil)
if err == nil {
render.JSON(w, r, res) // go-chi "render" pkg
} else {
next.ServeHTTP(w, r)
}
}
}
func main() {
r := chi.NewRouter()
r.Group(func(r chi.Router) {
r.Post("/graphql", Handler(supergraph, gqlgen))
})
}
QUESTIONS
Can I avoid these lines at all?
bodyBytes, _ := ioutil.ReadAll(r.Body) r.Body = ioutil.NopCloser(bytes.NewReader(bodyBytes))
Is there a better way to handle all this?
I know I can use a GraphQL gateway to join multiple schemas under the same endpoint, but is it really worth it? Is my idea/code really bad?
来源:https://stackoverflow.com/questions/62695231/using-two-handlers-for-a-graphql-project-handle-query-with-the-second-one-if-th