I’m trying out the clj and cljs transit libraries in a Clojurescript and Ring/Compojure demo, and while it kind of works I’m confused by something that I’m hoping someone can shed light on.
When I read about transit it seems like a basic use case is for transit-clj to encode Clojure forms on the server, which you can then send as application/transit+json to the client to be read by transit-cljs. The encoding server-side seems to work OK, but transit-cljs never reads the response – it fails with an error that you would get if you’re not reading valid JSON (“unexpected character at line 1 column 2 of the JSON”), or at least that’s what my searching tells me).
To read the data I just don’t use transit-cljs and treat the response as regular JSON, which oddly works OK.
This is the clj code on the server:
(def db (atom []))
(defn transit-out [data]
(let [out (ByteArrayOutputStream. 4096)
writer (transit/writer out :json)]
(transit/write writer data)
(.toString out)))
(defroutes app-routes
;....
(GET "/guestbook" []
(-> (transit-out @db)
(response)
(content-type "application/transit+json")))
(route/not-found "Not found."))
And the cljs client-side:
(defn get-guestbook []
(go
(let [data (<p! (.json (<p! (js/fetch "guestbook"))))
guestbook (.querySelector js/document "#entries")]
(set! (.-innerHTML guestbook) (clojure.string/join "<br>" data)))))
I thought I would have to use transit-cljs here to read the response of the js/fetch, but code like:
(let [data (transit/read (transit/reader :json) (<p! (js/fetch "guestbook")))] ....
fails with that error about ‘unexpected character’. So I’ve been just reading it as regular JSON instead.
Am I missing something basic to allow transit-cljs to read the response as transit+json?