Skip to content

Commit

Permalink
Fix with-retries, adapt the returned map
Browse files Browse the repository at this point in the history
  • Loading branch information
verberktstan committed Mar 5, 2024
1 parent 9259f05 commit dc350f3
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 16 deletions.
34 changes: 18 additions & 16 deletions src/swark/core.cljc
Original file line number Diff line number Diff line change
Expand Up @@ -89,18 +89,20 @@
(defn with-retries
{:added "0.1.41"
:arglist '([n f & args])
:doc "Returns the result of (apply f args) after running it n times. When
:doc "Returns the result of (apply f args) after retrying up to n times. When
something is thrown on the last try, returns the throwable map."}
[n f & args]
(-> n pos-int? assert)
(loop [n n, result nil]
(if (zero? n)
(or (jab Throwable->map result) result) ; Try to coerce to map if something is Thrown
(recur
(dec n)
(try
(apply f args)
(catch Throwable t t))))))
(loop [retries-left n]
(let [result (if (zero? retries-left)
(try
(apply f args)
(catch #?(:cljs :default :clj Throwable) t (Throwable->map t)))
(apply jab f args))]
(cond
(zero? retries-left) {:throwable result :retries-left retries-left :n n}
result {:result result :retries-left retries-left :n n}
:else (recur (dec retries-left))))))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Regarding strings
Expand All @@ -110,13 +112,13 @@
[input]
(letfn [(non-blank [s] (when-not (str/blank? s) s))]
(or
(when (keyword? input)
(->> ((juxt namespace name) input)
(keep identity)
(map ->str)
(str/join "/")))
(let [stringify (if (jab name input) name str)]
(some-> input stringify str/trim non-blank)))))
(when (keyword? input)
(->> ((juxt namespace name) input)
(keep identity)
(map ->str)
(str/join "/")))
(let [stringify (if (jab name input) name str)]
(some-> input stringify str/trim non-blank)))))

(defn unid
"Returns a unique string that does is not yet contained in the existing set."
Expand Down
13 changes: 13 additions & 0 deletions test/swark/core_test.clj
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,19 @@
{::test "Testdata"} (namespace ::this)
{} "unknown")))

(t/deftest with-retries
(t/testing "Returns a map with the :result, :n input and :retries-left"
(t/is (= {:result (inc 1)
:n 3
:retries-left 3}
(sut/with-retries 3 inc 1))))
(let [{:keys [throwable n retries-left]} (sut/with-retries 4 / 1 0)]
(t/testing "Returns the n input and n retries left"
(t/is (= 4 n))
(t/is (= retries-left 0)))
(t/testing "Returns a throwable in case of an error or exception"
(t/is (= #{:via :trace :cause} (-> throwable keys set))))))

(t/deftest ->str
(t/are [result input] (= result (sut/->str input))
"Hello, Swark!" "Hello, Swark!"
Expand Down

0 comments on commit dc350f3

Please sign in to comment.