@@ -93,3 +93,52 @@ The body of your handler might look like:
93
93
94
94
With the above, if we fetch greetings for two or more people anywhere in our GraphQL query,
95
95
all the calls to ` load-one ` will be collected and dispatched once.
96
+
97
+ ## Usage with pedestal
98
+
99
+ [ Pedestal] ( https://github.com/pedestal/pedestal ) is based on interceptors, so we can add the loaders
100
+ and clean them up before they get to the terminal handler.
101
+
102
+ Below is an example combining Pedestal with
103
+ [ lacinia-pedestal] ( https://github.com/walmartlabs/lacinia-pedestal ) that provides some
104
+ building blocks for convenience (e.g. the graphiql IDE).
105
+
106
+ ``` clojure
107
+ ; Create an interceptor that adds loaders to the request
108
+ ; and cleans them up after response is generated.
109
+
110
+ (def attach-loaders
111
+ (let [cleanup (fn [context]
112
+ (when-let [loaders (get-in context [:request :loaders ])]
113
+ (doseq [[k ld] @loaders]
114
+ (println " closing loader: " k)
115
+ (.close @ld)))
116
+ context)]
117
+ {:name ::attach-loaders
118
+ :enter (fn [context] (assoc-in context [:request :loaders ] (atom (create-loaders ))))
119
+ :leave cleanup
120
+ :error cleanup}))
121
+
122
+
123
+ ; Handle the graphql request, passing the loaders into the graphql context
124
+
125
+ (def graphql-handler [req]
126
+ (let [{:keys [query variables]} (:json-params req)
127
+ result (g/execute graphql/schema query variables (select-keys req [:loaders ]))]
128
+ {:status 200
129
+ :body result
130
+ :headers {}}))
131
+
132
+
133
+ ; Basic routing for graphql API and IDE, transforming json request and response.
134
+
135
+ (def routes
136
+ (let [asset-path " /assets/graphiql" ]
137
+ (into #{[" /graphql" :post [(io.pedestal.http.body-params/body-params )
138
+ io.pedestal.http/json-body
139
+ attach-loaders
140
+ `graphql-handler]]
141
+ [" /graphiql" :get (lp/graphiql-ide-handler {:asset-path asset-path
142
+ :api-path " /graphql" }) :route-name :graphiql ]}
143
+ (lp/graphiql-asset-routes asset-path))))
144
+ ```
0 commit comments