Skip to content

Commit

Permalink
Add field in http-messages with message as json
Browse files Browse the repository at this point in the history
  • Loading branch information
mdemare committed Nov 11, 2024
1 parent 97624cb commit 8006779
Showing 1 changed file with 28 additions and 13 deletions.
41 changes: 28 additions & 13 deletions src/nl/surf/eduhub_rio_mapper/endpoints/api.clj
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@

(ns nl.surf.eduhub-rio-mapper.endpoints.api
(:require [clojure.spec.alpha :as s]
[clojure.data.json :as json]
[clojure.string :as str]
[compojure.core :refer [GET POST]]
[compojure.route :as route]
Expand All @@ -32,6 +33,7 @@
[nl.surf.eduhub-rio-mapper.specs.ooapi :as ooapi-specs]
[nl.surf.eduhub-rio-mapper.specs.rio :as rio]
[nl.surf.eduhub-rio-mapper.utils.authentication :as authentication]
[nl.surf.eduhub-rio-mapper.utils.http-utils :as http-utils]
[nl.surf.eduhub-rio-mapper.utils.logging :refer [with-mdc wrap-logging]]
[nl.surf.eduhub-rio-mapper.utils.ooapi :as ooapi-utils]
[nl.surf.eduhub-rio-mapper.worker :as worker]
Expand Down Expand Up @@ -95,22 +97,35 @@
(assoc :status http-status/ok
:body (metrics/prometheus-render-metrics (count-queues-fn) (fetch-jobs-by-status) schac-home-to-name))))))

(defn json-request-headers? [headers]
(let [accept (headers "Accept")]
(and accept
(str/starts-with? accept "application/json"))))

;; For json requests (requests with a json Accept header) add a :json_res key with the
;; same content as the response, only with the json parsed, instead of as a raw string.
(defn add-parsed-json-response [{:keys [req res]}]
(let [res (select-keys res http-utils/http-message-res-keys)]
(cond-> {:req req :res res}
(json-request-headers? (:headers req))
(assoc :json_res (assoc res :body (json/read-str (:body res)))))))

(defn render-status-as-json [res show-http-messages? status]
(if (nil? status)
{:status http-status/not-found :body {:status :unknown}}
(merge res {:status http-status/ok
:body (assoc status
:http-messages (when show-http-messages?
(map add-parsed-json-response (:http-messages status))))})))

(defn wrap-status-getter
[app {:keys [status-getter-fn]}]
(fn status-getter [req]
(let [res (app req)]
(if-let [token (:token res)]
(with-mdc {:token token}
(if-let [status (status-getter-fn token)]
(assoc res
:status http-status/ok
:body (if (= "false" (get-in req [:params :http-messages] "false"))
(dissoc status :http-messages)
status))
(assoc res
:status http-status/not-found
:body {:status :unknown})))
res))))
(let [res (app req)
token (:token res)
show-http-messages? (= "true" (get-in req [:params :http-messages] "false"))]
(cond-> res
token (render-status-as-json show-http-messages? (status-getter-fn token))))))

(defn wrap-uuid-validator [app]
(fn uuid-validator [req]
Expand Down

0 comments on commit 8006779

Please sign in to comment.