Created
February 8, 2020 20:33
-
-
Save xfthhxk/c120802c88ad5918e36d9df69c04b211 to your computer and use it in GitHub Desktop.
Using fetch from ClojureScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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