From 67b61ba65a1495598129f6dc6aa371c7d6cf98b0 Mon Sep 17 00:00:00 2001 From: Bart Akeley Date: Fri, 20 Oct 2017 23:20:18 -0500 Subject: [PATCH] send responses as json --- project.clj | 3 ++- src/aretherecookies_server/handler.clj | 31 +++++++++++++++++++++----- 2 files changed, 28 insertions(+), 6 deletions(-) diff --git a/project.clj b/project.clj index 02e86a0..38772e0 100644 --- a/project.clj +++ b/project.clj @@ -8,7 +8,8 @@ [org.clojure/java.jdbc "0.7.3"] [org.postgresql/postgresql "42.1.4.jre6"] [com.mchange/c3p0 "0.9.5.2"] - [ring-middleware-format "0.7.2"]] + [ring-middleware-format "0.7.2"] + [org.clojure/data.json "0.2.6"]] :plugins [[lein-ring "0.9.7"]] :ring {:handler aretherecookies-server.handler/app} :profiles diff --git a/src/aretherecookies_server/handler.clj b/src/aretherecookies_server/handler.clj index 1f5f718..2bb1638 100644 --- a/src/aretherecookies_server/handler.clj +++ b/src/aretherecookies_server/handler.clj @@ -2,7 +2,8 @@ (:require [compojure.core :refer :all] [compojure.route :as route] [ring.middleware.defaults :refer [wrap-defaults site-defaults]] - [clojure.java.jdbc :as jdbc]) + [clojure.java.jdbc :as jdbc] + [clojure.data.json :as json]) (:import com.mchange.v2.c3p0.ComboPooledDataSource)) (def db-spec {:dbtype "postgresql" @@ -51,12 +52,32 @@ (jdbc/query @pooled-db [location-query]) -(defn food-items-handler [request] - (jdbc/query @pooled-db - [location-query])) +(defn uuid-to-string [key value] + (if (instance? java.util.UUID value) (.toString value) value)) + +(defn get-coords [item] + (get (json/read-str (get item :location)) "coordinates")) + +(defn build-lat-lng [[lng lat]] + (hash-map :longitude lng :latitude lat)) + +(defn parse-location [item] + (dissoc (merge item (build-lat-lng (get-coords item))) :location)) + +(defn food-items-to-json [response] + (map parse-location response)) + +(defn food-items-handler [location orderby filter] + (json/write-str + (hash-map + :orderby orderby + :filter filter + :fooditems (food-items-to-json (jdbc/query @pooled-db [location-query]))) + :value-fn uuid-to-string)) (defroutes app-routes - (GET "/fooditems" request (food-items-handler request))) + (GET "/fooditems" [location orderby filter] (food-items-handler location orderby filter)) + (GET "/echo" [location orderby filter] (str location orderby filter))) (def app (wrap-defaults app-routes site-defaults))