Skip to content

Commit 054546a

Browse files
committed
Document usage with pedestal
1 parent a224f52 commit 054546a

File tree

2 files changed

+50
-1
lines changed

2 files changed

+50
-1
lines changed

README.md

+49
Original file line numberDiff line numberDiff line change
@@ -93,3 +93,52 @@ The body of your handler might look like:
9393

9494
With the above, if we fetch greetings for two or more people anywhere in our GraphQL query,
9595
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+
```

pom.xml

+1-1
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
<modelVersion>4.0.0</modelVersion>
44
<groupId>tako</groupId>
55
<artifactId>tako</artifactId>
6-
<version>0.1.0-alpha1</version>
6+
<version>0.1.0-SNAPSHOT</version>
77
<name>tako</name>
88
<developers>
99
<developer>

0 commit comments

Comments
 (0)