Skip to content

Commit e2c76fb

Browse files
gburtchris-ramon
authored andcommitted
add an optional ResultCallbackFn
useful if you want to do logging based on the params or response
1 parent ca80078 commit e2c76fb

File tree

1 file changed

+27
-17
lines changed

1 file changed

+27
-17
lines changed

handler.go

Lines changed: 27 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -18,12 +18,15 @@ const (
1818
ContentTypeFormURLEncoded = "application/x-www-form-urlencoded"
1919
)
2020

21+
type ResultCallbackFn func(ctx context.Context, params *graphql.Params, result *graphql.Result, responseBody []byte)
22+
2123
type Handler struct {
22-
Schema *graphql.Schema
23-
pretty bool
24-
graphiql bool
25-
playground bool
26-
rootObjectFn RootObjectFn
24+
Schema *graphql.Schema
25+
pretty bool
26+
graphiql bool
27+
playground bool
28+
rootObjectFn RootObjectFn
29+
resultCallbackFn ResultCallbackFn
2730
}
2831
type RequestOptions struct {
2932
Query string `json:"query" url:"query" schema:"query"`
@@ -155,17 +158,22 @@ func (h *Handler) ContextHandler(ctx context.Context, w http.ResponseWriter, r *
155158
// use proper JSON Header
156159
w.Header().Add("Content-Type", "application/json; charset=utf-8")
157160

161+
var buff []byte
158162
if h.pretty {
159163
w.WriteHeader(http.StatusOK)
160-
buff, _ := json.MarshalIndent(result, "", "\t")
164+
buff, _ = json.MarshalIndent(result, "", "\t")
161165

162166
w.Write(buff)
163167
} else {
164168
w.WriteHeader(http.StatusOK)
165-
buff, _ := json.Marshal(result)
169+
buff, _ = json.Marshal(result)
166170

167171
w.Write(buff)
168172
}
173+
174+
if h.resultCallbackFn != nil {
175+
h.resultCallbackFn(ctx, &params, result, buff)
176+
}
169177
}
170178

171179
// ServeHTTP provides an entrypoint into executing graphQL queries.
@@ -177,11 +185,12 @@ func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
177185
type RootObjectFn func(ctx context.Context, r *http.Request) map[string]interface{}
178186

179187
type Config struct {
180-
Schema *graphql.Schema
181-
Pretty bool
182-
GraphiQL bool
183-
Playground bool
184-
RootObjectFn RootObjectFn
188+
Schema *graphql.Schema
189+
Pretty bool
190+
GraphiQL bool
191+
Playground bool
192+
RootObjectFn RootObjectFn
193+
ResultCallbackFn ResultCallbackFn
185194
}
186195

187196
func NewConfig() *Config {
@@ -202,10 +211,11 @@ func New(p *Config) *Handler {
202211
}
203212

204213
return &Handler{
205-
Schema: p.Schema,
206-
pretty: p.Pretty,
207-
graphiql: p.GraphiQL,
208-
playground: p.Playground,
209-
rootObjectFn: p.RootObjectFn,
214+
Schema: p.Schema,
215+
pretty: p.Pretty,
216+
graphiql: p.GraphiQL,
217+
playground: p.Playground,
218+
rootObjectFn: p.RootObjectFn,
219+
resultCallbackFn: p.ResultCallbackFn,
210220
}
211221
}

0 commit comments

Comments
 (0)