-
-
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
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 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}}}}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.