Last active
August 29, 2015 14:23
-
-
Save tylermorten/bc957a036e8f31bae4c1 to your computer and use it in GitHub Desktop.
repond-ajax
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(ns respond-ajax | |
(:require [io.pedestal.interceptor :as interceptor] | |
[cheshire.core :as json]) | |
(defn base-response [content-type status] | |
{:status (or status 200) | |
:headers {"Content-type" content-type}}) | |
(defmulti generate-response :content-type) | |
(defmethod generate-response "application/edn" [{:keys [obj status content-type]}] | |
(assoc (base-response content-type 200) :body (pr-str obj))) | |
(defmethod generate-response "application/json" [{:keys [obj status content-type]}] | |
(assoc (base-response content-type (or status 200)) | |
:body (json/generate-string obj))) | |
(defmethod generate-response :default [{:keys [obj status]}] | |
(assoc (base-response "text/plain" (or status 200)) :body (pr-str obj))) | |
(defn respond-ajax [result-fn] | |
"Creates an interceptor that generates a response based upon the content-type in the request" | |
(interceptor | |
{::name ::respond-ajax | |
:enter (fn [{:keys [request] :as context}] | |
(let [obj (result-fn request)] | |
(assoc context :response (generate-response (-> request | |
(merge {:obj obj :status 200}))))))})) | |
;; Example usage | |
;; some function that returns data | |
;; needs to take a request map for passage of | |
;; request params | |
(defn return-db-results [req] | |
(let [params (-> req :edn-params)] | |
(query-db params))) | |
;; in your defroutes | |
(defroutes routes | |
[[["/get-db-results" {:any [:db#get-results (respond-ajax return-db-results)]}]]]) | |
;; curl http://localhost:8080/get-db-results -H "Content-type: application/edn" -d "{:some-param-to-data :param}" | |
;; curl http://localhost:8080/get-db-results -H "Content-type: application/json" -d "{:some-param-to-data :param}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment