2
\$\begingroup\$

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?

\$\endgroup\$
2
  • 1
    \$\begingroup\$ Could you please include your imports or specify what libraries ls and time stand for? \$\endgroup\$ Commented Aug 28, 2016 at 17:47
  • \$\begingroup\$ @Phrancis They are described in text, right below the first code block. \$\endgroup\$ Commented Aug 28, 2016 at 17:50

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.