Skip to content

Instantly share code, notes, and snippets.

@imrekoszo
Last active November 10, 2015 17:11
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 imrekoszo/44671357f415b05f2c49 to your computer and use it in GitHub Desktop.
Save imrekoszo/44671357f415b05f2c49 to your computer and use it in GitHub Desktop.
yada wrapper to do "proper" return content negotiation for POST apis that return maps
(ns yadawrapper
(:require
[yada.body]
[yada.methods]
[yada.protocols]
[clj-time.core :refer [now]]
[clj-time.coerce :refer [to-date]]))
(defrecord ApiPostWrapperResource [domain-function result]
yada.protocols/ResourceProperties
(resource-properties [_]
{:representations [{:media-type #{"application/edn"
"application/json;q=0.9"
"text/html;q=0.8"}
:charset #{"UTF-8"}}]
:allowed-methods #{:post}})
(resource-properties [_ _] {:last-modified (to-date (now))})
yada.methods/Post
(POST [this ctx]
(-> ctx
(get-in [:parameters :body])
domain-function
(#(assoc this :result %))))
yada.methods/PostResult
(interpret-post-result [_ ctx]
(letfn [(yada-format-body-1 [ctx] "Copied from yada.methods/GetMethod"
(let [representation (get-in ctx [:response :representation])]
;; representation could be nil, for example, resource could be a java.io.File
(update-in ctx [:response :body] yada.body/to-body representation)))
(yada-format-body-2 [ctx] "Copied from yada.methods/GetMethod"
(let [content-length (yada.body/content-length (get-in ctx [:response :body]))]
(cond-> ctx content-length (assoc-in [:response :content-length] content-length))))]
(-> (assoc-in ctx [:response :body] result)
yada-format-body-1
yada-format-body-2))
))
; usage:
; (defn domain-hello [{name :name}] {:hello name :success true})
; (yada (->ApiPostWrapperResource domain-hello {}) {:parameters {:post {:body {:name String}}}})
@imrekoszo
Copy link
Author

It's probably not 100% correct and I'm not entirely sure what happens when something goes wrong but I'm very early into this development.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment