[FIX #2565] data-store: escape leading tildes in message content

This commit is contained in:
Vitaliy Vlasov 2017-12-05 20:27:10 +02:00 committed by Roman Volosovskyi
parent c8168e9ff0
commit b0b4226680
2 changed files with 41 additions and 3 deletions

View File

@ -84,11 +84,33 @@
(defn write [realm f]
(.write realm f))
(def transit-special-chars #{"~" "^" "`"})
(def transit-escape-char "~")
(defn to-be-escaped?
"Check if element is a string that begins
with a character recognized as special by Transit"
[e]
(and (string? e)
(contains? transit-special-chars (first e))))
(defn prepare-for-transit
"Following Transit documentation, escape leading special characters
in strings by prepending a ~. This prepares for subsequent
fetching from Realm where Transit is used for JSON parsing"
[message]
(let [walk-fn (fn [e]
(cond->> e
(to-be-escaped? e)
(str transit-escape-char)))]
(walk/postwalk walk-fn message)))
(defn create
([realm schema-name obj]
(create realm schema-name obj false))
([realm schema-name obj update?]
(.create realm (to-string schema-name) (clj->js obj) update?)))
(.create realm (to-string schema-name) (clj->js (prepare-for-transit obj)) update?)))
(defn save
([realm schema-name obj]

View File

@ -1,9 +1,25 @@
(ns status-im.test.data-store.realm.core
(:require [cljs.test :refer-macros [deftest is]]
(:require [cljs.test :refer-macros [deftest is testing]]
[status-im.data-store.realm.core :as core]))
(deftest serilization
(deftest serialization
(is (nil? (core/deserialize "")))
(is (nil? (core/deserialize "giberrish")))
(is (nil? (core/deserialize nil)))
(is (nil? (core/deserialize (core/serialize nil)))))
(deftest transit-preparation
(testing "Check if leading Transit special characters are properly escaped with tildes"
(let [data {:to-be-escaped1 "~bad string"
:to-be-escaped2 "^another bad string"
:to-be-escaped3 "`and another bad string"
:no-escaping "no escaping"
:vector-content ["a" "b" "c"]}
prepared-data (core/prepare-for-transit data)]
(is (= "~~bad string" (:to-be-escaped1 prepared-data)))
(is (= "~^another bad string" (:to-be-escaped2 prepared-data)))
(is (= "~`and another bad string" (:to-be-escaped3 prepared-data)))
(is (= "no escaping" (:no-escaping prepared-data)))
(is (= data (-> prepared-data
clj->js
core/internal-convert))))))