-
-
Notifications
You must be signed in to change notification settings - Fork 137
/
transit.cljc
92 lines (81 loc) · 2.17 KB
/
transit.cljc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
(ns fulcro.transit
#?(:clj
(:refer-clojure :exclude [ref]))
(:require [cognitect.transit :as t]
#?(:cljs [com.cognitect.transit :as ct])
[fulcro.tempid :as tempid #?@(:cljs [:refer [TempId]])])
#?(:clj
(:import [com.cognitect.transit
TransitFactory WriteHandler ReadHandler]
[fulcro.tempid TempId])))
#?(:cljs
(deftype TempIdHandler []
Object
(tag [_ _] "fulcro/tempid")
(rep [_ r] (. r -id))
(stringRep [_ _] nil)))
#?(:clj
(deftype TempIdHandler []
WriteHandler
(tag [_ _] "fulcro/tempid")
(rep [_ r] (. ^TempId r -id))
(stringRep [_ r] (. ^TempId r -id))
(getVerboseHandler [_] nil)))
#?(:cljs
(defn writer
([]
(writer {}))
([opts]
(t/writer :json
(assoc-in opts [:handlers TempId] (TempIdHandler.))))))
#?(:clj
(defn writer
([out]
(writer out {}))
([out opts]
(t/writer out :json
(assoc-in opts [:handlers TempId] (TempIdHandler.))))))
#?(:cljs
(defn reader
([]
(reader {}))
([opts]
(t/reader :json
(assoc-in opts
[:handlers "fulcro/tempid"]
(fn [id] (tempid/tempid id)))))))
#?(:clj
(defn reader
([in]
(reader in {}))
([in opts]
(t/reader in :json
(assoc-in opts
[:handlers "fulcro/tempid"]
(reify
ReadHandler
(fromRep [_ id] (TempId. id))))))))
(defn serializable?
"Checks to see that the value in question can be serialized by the default fulcro writer."
[v]
#?(:clj (try
(.write (writer (java.io.ByteArrayOutputStream.)) v)
true
(catch Exception e false))
:cljs (try
(.write (writer) v)
true
(catch :default e false))))
(comment
;; cljs
(t/read (reader) (t/write (writer) (tempid/tempid)))
;; clj
(import '[java.io ByteArrayOutputStream ByteArrayInputStream])
(def baos (ByteArrayOutputStream. 4096))
(def w (writer baos))
(t/write w (TempId. (java.util.UUID/randomUUID)))
(.toString baos)
(def in (ByteArrayInputStream. (.toByteArray baos)))
(def r (reader in))
(t/read r)
)