Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 477
Alex V Avatar asked Oct 25 '25 19:10

Alex V


2 Answers

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.

like image 194
rmm Avatar answered Oct 28 '25 20:10

rmm


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)))
like image 36
Laurence Chen Avatar answered Oct 28 '25 19:10

Laurence Chen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!