Skip to content

Commit

Permalink
Merge pull request #21 from jeluard/master
Browse files Browse the repository at this point in the history
Support for Rate Limiting
  • Loading branch information
Raynes committed Dec 27, 2012
2 parents 555f704 + ba3c8e8 commit eb14c22
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 3 deletions.
10 changes: 7 additions & 3 deletions src/tentacles/core.clj
Original file line number Diff line number Diff line change
Expand Up @@ -31,17 +31,21 @@
(map parse-link)
(into {})))

(defn merge-rate-limit [m h]
"Merges RateLimit values from headers into Json response"
(merge m (select-keys h [:X-RateLimit-Limit :X-RateLimit-Remaining])))

(defn safe-parse
"Takes a response and checks for certain status codes. If 204, return nil.
If 400, 422, 404, 204, or 500, return the original response with the body parsed
If 400, 401, 204, 422, 403, 404 or 500, return the original response with the body parsed
as json. Otherwise, parse and return the body if json, or return the body if raw."
[resp]
(if (#{400 401 204 422 404 500} (:status resp))
(if (#{400 401 204 422 403 404 500} (:status resp))
(update-in resp [:body] parse-json)
(let [links (parse-links (get-in resp [:headers "link"] ""))
content-type (get-in resp [:headers "content-type"])]
(if-not (.contains content-type "raw")
(with-meta (parse-json (:body resp)) {:links links})
(with-meta (merge-rate-limit (parse-json (:body resp)) (:headers resp)) {:links links})
(resp :body)))))

(defn update-req
Expand Down
13 changes: 13 additions & 0 deletions test/tentacles/core_test.clj
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
(ns tentacles.core-test
(:use clojure.test)
(:require [tentacles.core :as core]))

(deftest hitting-rate-limit-is-propagated
(is (= (:status (core/safe-parse {:status 403}))
403)))

(deftest rate-limit-details-are-propagated-when-defined
(is (contains? (core/safe-parse {:status 200 :X-RateLimit-Limit 20 :headers {"content-type" ""}}) :X-RateLimit-Limit)))

(deftest rate-limit-details-are-ignored-when-undefined
(is (not (contains? (core/safe-parse {:status 200 :headers {"content-type" ""}}) :X-RateLimit-Limit))))

0 comments on commit eb14c22

Please sign in to comment.