Using two handlers for a GraphQL project; handle query with the second one if the first one is not capable of

江枫思渺然 提交于 2021-01-29 10:17:16

问题


I'm trying to use both SuperGraph as-a-library and GqlGen.

So I have two handlers:

  1. the first one is SuperGraph; this checks that it can carry out the operation

  2. 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

  1. Can I avoid these lines at all?

      bodyBytes, _ := ioutil.ReadAll(r.Body)
      r.Body = ioutil.NopCloser(bytes.NewReader(bodyBytes))
    
  2. Is there a better way to handle all this?

  3. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!