Skip to content

Instantly share code, notes, and snippets.

@deadghost
Created September 25, 2018 08:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save deadghost/92915712227882f7bfe7d3af42988951 to your computer and use it in GitHub Desktop.
Save deadghost/92915712227882f7bfe7d3af42988951 to your computer and use it in GitHub Desktop.
(ns contact.api.v0.interceptor.coerce-body
(:require [cheshire.core :as json]
[io.pedestal.interceptor :refer [interceptor]]))
(defn accepted-type [context]
(get-in context [:request :accept :field] "application/json"))
(defn transform-content [body content-type]
(case content-type
"text/html" body
"text/plain" body
"application/edn" (pr-str body)
"application/json" (json/generate-string body)))
(defn coerce-to [response content-type]
(-> response
(update :body transform-content content-type)
(assoc-in [:headers "Content-Type"] content-type)))
(def coerce-body
(interceptor
{:name ::coerce-body
:leave
(fn [context]
(print "coerce-body: ")
(pr (accepted-type context))
(cond-> context
(nil? (get-in context [:response :headers "Content-Type"]))
(update-in [:response] coerce-to (accepted-type context))))}))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment