Skip to content

Instantly share code, notes, and snippets.

@jdf-id-au
Last active September 10, 2023 09:32
Show Gist options
  • Select an option

  • Save jdf-id-au/2e91fb63ce396b722c1d6770154f1815 to your computer and use it in GitHub Desktop.

Select an option

Save jdf-id-au/2e91fb63ce396b722c1d6770154f1815 to your computer and use it in GitHub Desktop.

Revisions

  1. jdf-id-au revised this gist Aug 21, 2019. No changes.
  2. jdf-id-au created this gist Aug 21, 2019.
    78 changes: 78 additions & 0 deletions transit-connection.cljc
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,78 @@
    (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