aretherecookies-server/src/aretherecookies/handler.clj
Bart Akeley 7af08e122b new /addfooditem route handler, query
*needs re-run of ddl
2018-02-10 11:49:54 -06:00

52 lines
1.9 KiB
Clojure

(ns aretherecookies.handler
(:require [aretherecookies.db :refer [query-food-items
insert-quantity
create-food-item]]
[aretherecookies.parsers :refer [parse-special-types parse-location]]
[clojure.data.json :as json]
[clojure.string :as str]
[buddy.auth :refer [authenticated? throw-unauthorized]]))
(defn safe-json
"converts hashmaps into a JSON string suitable for a network response"
[data]
(json/write-str data :value-fn parse-special-types))
(defn bad-request
"returns a HTTP 404 error with the supplied body"
[body]
{:status 400 :body (safe-json body)})
(defn food-items-handler [req]
(println "/fooditems ---->" (:body req))
(let [{body :body} req]
(safe-json
(hash-map
:filter (:filter body)
:fooditems (map parse-location (query-food-items body))))))
(defn quantity-handler [req]
(let [{{foodItemId :foodItemId quantity :quantity} :body} req]
(if-not (authenticated? req) (throw-unauthorized))
(println "/quantity ---->" foodItemId quantity)
(json/write-str
(insert-quantity {:foodItemId foodItemId :quantity quantity})
:value-fn parse-special-types)))
(def required-keys [:name :placeId :latitude :longitude :category :quantity])
(defn get-missing-keys
[foodItem]
(filter #(get foodItem %) required-keys))
(defn add-food-item-handler
"validate food item fields from request and insert into database returning newly created item"
[req]
(println "/addfooditem ---->" (:body req))
(if-not (authenticated? req) (throw-unauthorized))
(let [food-item (:body req) missing-keys (get-missing-keys food-item)]
(if (< (count missing-keys) 0)
(bad-request {"missingkeys" missing-keys})
(as->
(create-food-item food-item) %
(map parse-location %)
(safe-json %)))))