Permalink
Browse files

Merge pull request #21 from jeluard/master

Support for Rate Limiting
  • Loading branch information...
2 parents 555f704 + ba3c8e8 commit eb14c22bd77bff2f5a888e83f85c9eb618e3651f @Raynes committed Dec 27, 2012
Showing with 20 additions and 3 deletions.
  1. +7 −3 src/tentacles/core.clj
  2. +13 −0 test/tentacles/core_test.clj
View
@@ -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
@@ -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.