Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support for Rate Limiting #21

Merged
merged 2 commits into from
Dec 27, 2012
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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))))