Skip to content

Instantly share code, notes, and snippets.

@ah45
Created April 17, 2015 14:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ah45/9774016d4eaf0f7a0873 to your computer and use it in GitHub Desktop.
Save ah45/9774016d4eaf0f7a0873 to your computer and use it in GitHub Desktop.
Clojurescript Transit XHR Handler
(ns thoth.transit-xhr
(:require [cljs-time.format :as tf]
[cognitect.transit :as tr]
[com.cognitect.transit.types :as trt]
[goog.events :as events])
(:import [goog.net XhrIo]))
(def http-methods
"The HTTP request codes we support Transit payloads in."
{:get "GET"
:post "POST"})
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Encoding/decoding
(def date-formatter (:date tf/formatters))
(def write-handlers
{goog.date.Date
(tr/write-handler
(fn [d] "Date")
(fn [d] (tf/unparse-local-date date-formatter d)))})
(def read-handlers
{"f"
(tr/read-handler
(fn [v] (trt/floatValue v)))
"Date"
(tr/read-handler
(fn [d] (tf/parse-local-date d)))})
(def transit-json-reader
"A transit+json reader, using our custom handlers."
(tr/reader :json {:handlers read-handlers}))
(def transit-json-writer
"A transit+json writer, using our custom handlers."
(tr/writer :json {:handlers write-handlers}))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Public
(defn transit-xhr
"Makes an asynchronous HTTP request, encoding/decoding the data
sent/received as `transit+json`. Calls `on-complete` with the returned
(decoded) data."
[{:keys [method url data on-complete]}]
(let [xhr (XhrIo.)]
(events/listen
xhr goog.net.EventType.COMPLETE
(fn [e]
(let [resp (.getResponseText xhr)
data (tr/read transit-json-reader resp)]
(on-complete data))))
(. xhr
(send url
(http-methods method)
(when data (tr/write transit-json-writer data))
#js {"Content-Type" "application/transit+json"}))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment