Search code examples
clojureclojurescriptfetch-apiclojurescript-javascript-interop

How to I get the body text of a Response object returned by the fetch API in ClojureScript?


I'm trying to use the Github Gist API to get a list of all of my Gists like so:

(ns epi.core)

(.then  (.fetch js/window "https://api.github.com/users/seisvelas/gists")
        (fn [data] (.log js/epi data)))

js/epi is just console.log except provided by the blogging platform I'm using (epiphany.pub).

When I call that API from curl it works fine; however, when done in cljs instead of giving me the body of the response, this gives me [object Response]. Does anyone know how I can get the body text of the response?


Solution

  • TL;DR

    (-> (.fetch js/window "https://api.github.com/users/seisvelas/gists")
      (.then #(.json %))  ; Get JSON from the Response.body ReadableStream
      (.then #(.log js/epi %))
    

    is what I'd write


    From ClojureScript, a JavaScript call like data.body() can be invoked with

    (.body data)
    

    and a JavaScript property access like data.body with

    (.-body data)
    

    One of those should work in your case. However, the fetch API requires a bit more if you want to get JSON from the body, which I assume you do based on the endpoint.

    If you're dealing with promise chains, you might also want to consider using -> (thread-first) so it reads top to bottom.

    See this Gist for more about threading promise chains.