Anton Harald
Anton Harald

Reputation: 5924

pass date from clojure server to cljs frontend via transit format

A clojure server reads a datetime column from a mysql database. By using jdbc this action usually returns an instance of java.sql.Timestamp

I'm bringing this data to a frontend via the transit format. One could coerce the date to a timestamp and parse it on the frontend for further processing for e.g. the library cljs-time. Is this the way to go or is there another more convenient approach?

Upvotes: 1

Views: 397

Answers (1)

Daniel Compton
Daniel Compton

Reputation: 14549

You can see the default type mappings in transit-cljs here. By default Transit time values are mapped to JavaScript Dates. I much prefer to have the Dates mapped to goog.Date.UtcDateTime. There's docs on extending Transit Read and Write handlers, but here's what we use:

(def transit-readers
  {:handlers
   {"m" (transit/read-handler (fn [s] (UtcDateTime.fromTimestamp s)))
    "u" uuid}})

(def transit-writers
  {:handlers
   {UtcDateTime (transit/write-handler
                  (constantly "m")
                  (fn [v] (.getTime v))
                  (fn [v] (str (.getTime v))))}})

Upvotes: 1

Related Questions