diff --git a/src/yohoho/core.clj b/src/yohoho/core.clj index 3e23923..c8741e6 100644 --- a/src/yohoho/core.clj +++ b/src/yohoho/core.clj @@ -6,6 +6,8 @@ (:gen-class)) + +;; Handlers ------------------------------------------------------- (defn ahoy-handler [_] {:status 200 @@ -29,6 +31,22 @@ :body {:id id, :name name, :email email}})) +;; Custom middleware ---------------------------------------------- +(defn wrap-content-type-json + "Middleware that checks is a POST request is bring sent data as JSON" + [handler] + (fn [request] + (let [http-verb (:request-method request) + is-post? (= :post http-verb) + content-type (get-in request [:headers "content-type"]) + is-json? (= "application/json" content-type)] + (cond (not is-post?) (handler request) + (and is-post? is-json?) (handler request) + :else {:status 415 + :body {:error "Unsupported Media Type" + :message "Content-Type must be application/json"}})))) + +;; Routing -------------------------------------------------------- (def app (ring/ring-handler (ring/router @@ -37,13 +55,15 @@ :post post-items-handler}]] ;; Use muuntaja middleware to automatically decode JSON {:data {:muuntaja m/instance - :middleware [muuntaja/format-middleware]}}) + :middleware [wrap-content-type-json + muuntaja/format-middleware]}}) ;; Default route: anything not explicitely handled should give a 404 (ring/create-default-handler {:not-found (constantly {:status 404 :body {:error "Not Found"}})}))) +;; Entry point ---------------------------------------------------- (defn -main "HolidayPirates take-home assignement. Goal: build a (very) small REST API that exposes to endpoints."