I've defined myself a function for caching requests and their responses in a browser environment; I'm using ClojureScript.
(defn make-requester [namespace time-limit fun]
(fn [cont & params]
(let [cache (ls/get-item namespace)
key (pr-str params)]
(if
(and
(contains? cache key)
(time/fresh? time-limit (:time (get cache key))))
(cont (:value (get cache key)))
(apply fun
(concat [(fn [value]
(let [time (time/get-time)
updated (assoc cache key {:value value :time time})]
(ls/set-item namespace updated)
(cont value)))]
params))))))
Where
ls/get-item
, ls/set-item
are just getting/setting items in the local storage
and the time/
functions do what they say. The http/
functions are from the cljs-http module.
Example of using this:
(def get-status
(make-requester
"status"
30000 ; 30 seconds
(fn [cont url params]
(go
(cont (:body (<! (http/get url params))))))))
(get-status
println
"http://jsonplaceholder.typicode.com/posts/1"
{:with-credentials? false})
This is the first time I'm doing any async operations in ClojureScript and I'd like to improve the code in any way. Can the async bit be improved? Can the apply
bit be improved? Is there no spread ...
shorthand? Is this the correcy way to serialzie/deserialize clojure data structures? Is the code Clojure-y enough?
ls
andtime
stand for? \$\endgroup\$