Skip to content

Instantly share code, notes, and snippets.

@mkrcah
Last active December 19, 2023 15:49
Show Gist options
  • Save mkrcah/50554447517520f4c4954f9430d0f1fa to your computer and use it in GitHub Desktop.
Save mkrcah/50554447517520f4c4954f9430d0f1fa to your computer and use it in GitHub Desktop.
exploring APIs with REPL
(ns client.json-rest-client
(:require [clojure.data.json :as json]
[hato.client :as http]
[medley.core :as medley]))
(defn full-req [req server-conf]
(-> req
(dissoc :rel-path :body)
(medley/assoc-some :url (str (:server-url server-conf) (:rel-path req))
:accept :json
:throw-exceptions? false
:content-type (when (:body req) :json)
:form-params (:body req)
:basic-auth (:basic-auth server-conf))))
(defn parse-json-body [res]
(some-> res
:body
(json/read-str :key-fn keyword)))
(defn friendly-res [res]
(-> res
(medley/assoc-some :parsed-body (parse-json-body res))
(medley/dissoc-in [:http-client]
[:version]
[:request-time]
[:headers]
[:body]
[:content-type-params]
[:request :user-info]
[:request :throw-exceptions?]
[:request :server-port]
[:request :http-request]
[:request :server-name]
[:request :scheme])))
; v1 has a side-effect at the start, but requires a full request
(defn req-v1! [full-req]
(-> full-req
(http/request)
(friendly-res))),
; v2 has a side-effect married from both sides to prepping the request and prepping the response
(defn req-v2! [req server-conf]
(-> req
(full-req server-conf)
(http/request)
(friendly-res)))
(comment
(def server-conf {:server-url "http://localhost:8109"})
(def get-status {:method :get :path "/status"})
; with v1, I can only evaluate the `full-req` form and if I want, proceed to the whole `req-v1!`
(req-v1! (full-req get-status server-conf))
; with v2, cannot see the full-req anymore; v2 complects more logic
(req-v2! get-status server-conf))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment