Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Manipulate response handlers adjusts #21

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 5 additions & 4 deletions src/untangled/server/core.clj
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
[a->b b->c]
(reduce (fn [result k] (assoc result k (->> k (get a->b) (get b->c)))) {} (keys a->b)))

(defn augment-response [core-response ring-response-fn]
(defn augment-response
"Augments the Ring response that's returned from the handler.

Use this function when you need to add information into the handler response, for
Expand All @@ -39,9 +39,10 @@
))})

If your parser has multiple responses with `augment-response`, they will be applied
in order, the first one will receive an empty map as input. Only root keys of your
response will be checked for augmented response.
"
in order, the first one will receive an empty map as input. Only top level values
of your response will be checked for augmented response."
[core-response ring-response-fn]
(assert (instance? clojure.lang.IObj core-response) "Scalar values can't be augmented.")
(with-meta core-response {::augment-response ring-response-fn}))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Expand Down
9 changes: 6 additions & 3 deletions src/untangled/server/impl/components/handler.clj
Original file line number Diff line number Diff line change
Expand Up @@ -82,8 +82,11 @@
(assoc acc k v)))
{} resp))

(defn collect-response [data]
(->> (keep #(some-> (second %) meta :untangled.server.core/augment-response) data)
(defn augment-map
"Parses response the top level values processing the augmented response. This function
expects the parser mutation results to be raised (use the raise-response function)."
[response]
(->> (keep #(some-> (second %) meta :untangled.server.core/augment-response) response)
(reduce (fn [response f] (f response)) {})))

(defn api
Expand All @@ -95,7 +98,7 @@
[{:keys [transit-params parser env] :as req}]
(let [parse-result (try (raise-response (parser env transit-params)) (catch Exception e e))]
(if (valid-response? parse-result)
(merge {:status 200 :body parse-result} (collect-response parse-result))
(merge {:status 200 :body parse-result} (augment-map parse-result))
(process-errors parse-result))))

(defn generate-response
Expand Down