Last active
September 10, 2023 09:32
-
-
Save jdf-id-au/2e91fb63ce396b722c1d6770154f1815 to your computer and use it in GitHub Desktop.
Sketch for connecting henryw374/time-literals to transit
This file contains 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 transit-connection | |
"Connect time-literals to transit." | |
(:require [time-literals.read-write] | |
#?(:cljs [java.time :refer [Period | |
LocalDate | |
LocalDateTime | |
ZonedDateTime | |
OffsetTime | |
Instant | |
OffsetDateTime | |
ZoneId | |
DayOfWeek | |
LocalTime | |
Month | |
Duration | |
Year | |
YearMonth]])) | |
#?(:clj (:import (java.io ByteArrayOutputStream ByteArrayInputStream) | |
(java.time Period | |
LocalDate | |
LocalDateTime | |
ZonedDateTime | |
OffsetTime | |
Instant | |
OffsetDateTime | |
ZoneId | |
DayOfWeek | |
LocalTime | |
Month | |
Duration | |
Year | |
YearMonth)))) | |
(def time-classes | |
{'period Period | |
'date LocalDate | |
'date-time LocalDateTime | |
'zoned-date-time ZonedDateTime | |
'offset-time OffsetTime | |
'instant Instant | |
'offset-date-time OffsetDateTime | |
'time LocalTime | |
'duration Duration | |
'year Year | |
'year-month YearMonth | |
'zone ZoneId | |
'day-of-week DayOfWeek | |
'month Month}) | |
(def write-handlers | |
{:handlers | |
(into {} | |
(for [[tick-class host-class] time-classes] | |
[host-class (transit/write-handler (constantly (name tick-class)) str)]))}) | |
(def read-handlers | |
{:handlers | |
(into {} (for [[sym fun] time-literals.read-write/tags] | |
[(name sym) (transit/read-handler fun)]))}) ; omit "time/" for brevity | |
(defn ->transit "Encode data structure to transit." | |
[arg] | |
#?(:clj (let [out (ByteArrayOutputStream.) | |
writer (transit/writer out :json write-handlers)] | |
(transit/write writer arg) | |
(.toString out)) | |
:cljs (transit/write (transit/writer :json write-handlers) arg))) | |
(defn <-transit "Decode data structure from transit." | |
[json] | |
#?(:clj (try (let [in (ByteArrayInputStream. (.getBytes json)) | |
reader (transit/reader in :json read-handlers)] | |
(transit/read reader)) | |
(catch Exception e | |
(log/warn "Invalid message" json (:cause (Throwable->map e))) | |
:invalid-message)) | |
:cljs (transit/read (transit/reader :json read-handlers) json))) | |
; TODO catch js errors |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment