about summary refs log tree commit diff
diff options
context:
space:
mode:
authorMorgan Astra <m@morganastra.me>2018-11-16 14:14:13 -0800
committerMorgan Astra <m@morganastra.me>2018-11-16 14:14:13 -0800
commit759e1279d103ebebd3081fa10d9f3622f7a9f2b8 (patch)
tree1f0c4d912571b1c6ba621d90243e3750d1b39840
parent647c396d49b0091d5f1e077e2d0b8c275860ebe0 (diff)
parentb0eac61d82c9e03cf9b2eb646b3acabb49c02acb (diff)
Merge branch 'json-api' of https://github.com/SomeHats/pronoun.is into SomeHats-json-api
-rw-r--r--src/pronouns/pages.clj21
-rw-r--r--src/pronouns/web.clj12
2 files changed, 25 insertions, 8 deletions
diff --git a/src/pronouns/pages.clj b/src/pronouns/pages.clj
index 283a34b..e629329 100644
--- a/src/pronouns/pages.clj
+++ b/src/pronouns/pages.clj
@@ -15,7 +15,8 @@
 ;; along with this program.  If not, see <https://www.gnu.org/licenses/>
 
 (ns pronouns.pages
-  (:require [clojure.string :as s]
+  (:require [clojure.data.json :as json]
+            [clojure.string :as s]
             [pronouns.config :refer [pronouns-table]]
             [pronouns.util :as u]
             [hiccup.core :refer :all]
@@ -215,11 +216,23 @@
                         new-path))]))]
        (footer-block)]])))
 
-(defn pronouns [params]
+(defn pronouns [params format-fn not-found-fn]
   (let [path (params :*)
         param-alts (u/vec-coerce (or (params "or") []))
         path-alts (s/split path #"/:[oO][rR]/")
         pronouns (lookup-pronouns (concat path-alts param-alts))]
     (if (seq pronouns)
-      (format-pronoun-examples pronouns)
-      (not-found path))))
+      (format-fn pronouns)
+      (not-found-fn path))))
+
+(defn format-pronoun-json [& pronouns]
+  (json/write-str pronouns))
+
+(defn not-found-json []
+  (json/write-str {:error "Not found"}))
+
+(defn pronouns-json [path pronouns-table]
+  (pronouns params format-pronoun-json not-found-json))
+
+(defn pronouns-html [path pronouns-table]
+  (pronouns params format-pronoun-examples not-found))
diff --git a/src/pronouns/web.clj b/src/pronouns/web.clj
index 2c348c0..6321198 100644
--- a/src/pronouns/web.clj
+++ b/src/pronouns/web.clj
@@ -47,10 +47,14 @@
      :headers {"Content-Type" "text/css"}
      :body (slurp (io/resource "pronouns.css"))})
 
-  (GET "/*" {params :params}
-       {:status 200
-        :headers {"Content-Type" "text/html"}
-        :body (pages/pronouns params)})
+  (GET "/*" {params :params headers :headers}
+       (if (= "application/json" (s/lower-case (get headers "accept")))
+         {:status 200
+          :headers {"Content-Type" "application/json"}
+          :body (pages/pronouns-json params pronouns-table)}
+         {:status 200
+          :headers {"Content-Type" "text/html"}
+          :body (pages/pronouns params pronouns-table)}))
 
   (ANY "*" []
        (route/not-found (slurp (io/resource "404.html")))))