Add async storage wrapper

Signed-off-by: Gheorghe Pinzaru <feross95@gmail.com>
This commit is contained in:
Gheorghe Pinzaru 2020-12-09 11:17:28 +03:00
parent 86d7b79175
commit 09822e142b
No known key found for this signature in database
GPG Key ID: C9A094959935A952
2 changed files with 57 additions and 0 deletions

View File

@ -0,0 +1,46 @@
(ns status-im.async-storage.core
(:require [re-frame.core :as re-frame]
[taoensso.timbre :as log]
[goog.functions :as f]
[status-im.async-storage.transit :refer [clj->transit transit->clj]]
["@react-native-community/async-storage" :default async-storage]))
(def ^:private debounce-ms 250)
(def key->string str)
(defn- set-item! [key value]
(-> ^js async-storage
(.setItem (key->string key)
(clj->transit value))
(.catch (fn [error]
(log/error "[async-storage]" error)))))
(defn- set-item-factory
[]
(let [tmp-storage (atom {})
debounced (f/debounce (fn []
(doseq [[k v] @tmp-storage]
(swap! tmp-storage dissoc k)
(set-item! k v))) debounce-ms)]
(fn [items]
(swap! tmp-storage merge items)
(debounced))))
(defn- get-items [keys cb]
(-> ^js async-storage
(.multiGet (to-array (map key->string keys)))
(.then (fn [^js data]
(cb (->> (js->clj data)
(map (comp transit->clj second))
(zipmap keys)))))
(.catch (fn [error]
(cb nil)
(log/error "[async-storage]" error)))))
(re-frame/reg-fx ::set! (set-item-factory))
(re-frame/reg-fx
::get
(fn [{:keys [keys cb]}]
(get-items keys cb)))

View File

@ -0,0 +1,11 @@
(ns status-im.async-storage.transit
(:require [cognitect.transit :as transit]
[taoensso.timbre :as timbre]))
(def reader (transit/reader :json))
(def writer (transit/writer :json))
(defn clj->transit [o] (transit/write writer o))
(defn transit->clj [o] (try (transit/read reader o)
(catch :default e
(timbre/error e))))