Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use RequestCallbackFn to manage ctx, customise HTTP-headers and use DataLoader #1

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 14 additions & 28 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import (

"github.com/graph-gophers/dataloader"
"github.com/graphql-go/graphql"
"github.com/graphql-go/handler"
"github.com/michurin/handler"
"github.com/mxk/go-sqlite/sqlite3"
)

Expand Down Expand Up @@ -62,35 +62,20 @@ func sql(sql string) []sqlite3.RowMap {
return result
}

// ----- http -----

type gtHandler struct {
origHandler http.Handler
}
// ----- util -----

func (h *gtHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// you can set you own header for tracing etc
w.Header().Add("X-Michurin", "Here!")
// hacks for graphql-cli
func requestCallbackFn(ctx context.Context, w http.ResponseWriter, r *http.Request) context.Context {
w.Header().Add("X-Michurin", "Ok")
if origin := r.Header.Get("Origin"); origin != "" {
w.Header().Add("Access-Control-Allow-Origin", origin)
}
w.Header().Add("Access-Control-Allow-Headers", "Content-Type,X-Apollo-Tracing")
if r.Method == http.MethodOptions {
// just call for schema
h.origHandler.ServeHTTP(w, r)
} else {
// fill request context
h.origHandler.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), "dataloaders", NewLoaders())))
if r.Method != http.MethodOptions {
ctx = context.WithValue(ctx, "dataloaders", NewLoaders())
}
return ctx
}

func handlerWrapper(h http.Handler) *gtHandler {
return &gtHandler{h}
}

// ----- util -----

func getLoaderFnByName(p graphql.ResolveParams, name string, key dataloader.Key) dataloader.Thunk {
return p.Context.Value("dataloaders").(map[string]*dataloader.Loader)[name].Load(p.Context, key)
}
Expand Down Expand Up @@ -490,12 +475,13 @@ func main() {
panic(err)
}

handler := handlerWrapper(handler.New(&handler.Config{
Schema: &schema,
Pretty: true,
GraphiQL: true,
Playground: true,
}))
handler := handler.New(&handler.Config{
Schema: &schema,
Pretty: true,
GraphiQL: true,
Playground: true,
RequestCallbackFn: requestCallbackFn,
})
http.Handle("/gql", handler)

fmt.Println(`
Expand Down