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

1.7k Views Asked by At

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?

3

There are 3 best solutions below

0
On BEST ANSWER

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.

0
On

Seems like .fetch returns a Response object, and you need to get the attribute body from it for the body. https://developer.mozilla.org/en-US/docs/Web/API/Response

Something like (.body data)

0
On

There is a library wrapping js fetch API called lamdaisland.fetch. This library uses transit as default encoding format, so you need to specify accept format when working with github API.

This library contains kitchen-async.promise as its dependency, so you can require the kitchen-async.promise in your ClojureScript source code.

(ns fetch.demo.core
  (:require [kitchen-async.promise :as p]
            [lambdaisland.fetch :as fetch]))

(p/try
  (p/let [resp (fetch/get
                "https://api.github.com/users/seisvelas/gists"
                {:accept :json
                 :content-type :json})]
    (prn (:body resp)))
  (p/catch :default e
     ;; log your exception here
    (prn :error e)))