standardizes routing; adds check for request method

This commit is contained in:
Richard Harrington 2014-10-12 11:29:02 -04:00
parent ca7b2dfb4b
commit 8923ee9ef7
2 changed files with 32 additions and 22 deletions

View File

@ -29,7 +29,7 @@
(take 5))) (take 5)))
(defn add-game (defn add-game
"a function to update the games-store atom state. "a function to update the games-store atom state.
It keeps a running store of games, which is added It keeps a running store of games, which is added
to upon request from a browser, who is then to upon request from a browser, who is then
assigned an id number" assigned an id number"
@ -54,28 +54,34 @@
(def games-store (atom {:next-id 0 (def games-store (atom {:next-id 0
:games {}})) :games {}}))
(defn consistently-typed-re-matches [re s]
(when-let [match (re-matches re s)]
(if (string? match) [match] match)))
(defn handler [request] (defn handler [{:keys [uri query-params request-method] :as request}]
(let [route (fn [acceptable-request-method re action]
(let [match (re-matches #"\/worlds\/(\d+)\/(\d+)" (request :uri))] (when (= request-method acceptable-request-method)
(if match (when-let [[_ & url-params] (consistently-typed-re-matches re uri)]
(let [[_ id n] match] (apply action url-params))))]
(response (take-drop-send (or
games-store (route :get #"\/worlds\/(\d+)\/(\d+)"
(Integer/parseInt id) (fn [id n]
(Integer/parseInt n)))) (response (take-drop-send
games-store
(case (request :uri) (Integer/parseInt id)
"/program-names" (response (Integer/parseInt n)))))
{:names (map name (keys source-programs/programs))}) (route :get #"\/program-names"
(fn []
"/init" (let [programs ((request :query-params) "programs") (response
next-id (:next-id @games-store)] {:names (map name (keys source-programs/programs))})))
(swap! games-store add-game programs) (route :get #"\/init"
(response {:id next-id (fn []
:game-info game-info})) (let [programs (query-params "programs")
next-id (:next-id @games-store)]
(not-found "Not Found"))))) (swap! games-store add-game programs)
(response {:id next-id
:game-info game-info}))))
(not-found "Not Found"))))
(def app (def app
(-> handler (-> handler

View File

@ -14,6 +14,10 @@
(let [response (app (mock/request :get "/invalid"))] (let [response (app (mock/request :get "/invalid"))]
(is (= (:status response) 404)))) (is (= (:status response) 404))))
(testing "unsupported http request method"
(let [response (app (mock/request :put "/program-names"))]
(is (= (:status response) 404))))
(testing "files" (testing "files"
(let [response (app (mock/request :get "/index.html"))] (let [response (app (mock/request :get "/index.html"))]
(is (= (:status response) 200)) (is (= (:status response) 200))