Skip to content

Instantly share code, notes, and snippets.

@xfthhxk
Created February 8, 2020 20:33
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xfthhxk/c120802c88ad5918e36d9df69c04b211 to your computer and use it in GitHub Desktop.
Save xfthhxk/c120802c88ad5918e36d9df69c04b211 to your computer and use it in GitHub Desktop.
Using fetch from ClojureScript
(ns js-fetch
(:require [promesa.core :as p]
[clojure.string :as str])
(defn serialize
[content-type data]
(pr-str data))
(defn deserialize
[content-type text]
(cljs.reader/read-string text))
(defn fetch
"Returns promise a map with keys :headers and :body."
[{:as args :keys [method uri params headers]}]
(let [{:keys [content-type]} headers
state (atom {})
method (str/lower-case (name method))
opts (cond-> {:method method
:headers headers
:mode "cors"}
(and (not (#{"get" "head"} method))
params)
(assoc :body (serialize content-type params))
true clj->js)]
;; (log/infof "fetch args: %s" args)
;; (log/infof "fetch opts: %s" opts)
;; (.log js/console opts)
(-> (js/fetch uri opts)
(p/then (fn [response]
(let [headers (aget response "headers")]
(swap! state assoc :headers
(reduce (fn [m k]
(assoc m k (.get headers k)))
{}
(es6-iterator-seq (.keys headers)))))
(.text response)))
(p/then (fn [text]
(let [{:keys [content-type]} (:headers @state)
body (deserialize content-type text)]
{:headers headers
:body body}))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment