Created
June 9, 2023 06:41
-
-
Save ignorabilis/e5f7aea00f6506131aaa6e11df964f43 to your computer and use it in GitHub Desktop.
Declaratively define endpoints
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
(def api-defs | |
{:moogle | |
{:base-url "https://moogle.com" | |
:endpoints {:endpoint-a | |
{:method :post | |
:path ["/a/b/:id"] | |
:custom-headers-def {:header/X-cb-something-something :required}}}}}) | |
(defn construct-headers [custom-headers-def custom-headers] | |
(reduce | |
(fn [acc [k v]] | |
(let [header-val (get custom-headers (name k))] | |
(cond | |
(and (= v :required) (nil? header-val)) ;; this is an error obvs | |
(assoc acc :error "Required header missing") | |
(and (= v :optional) (nil? header-val)) | |
acc | |
header-val | |
(assoc acc (name k) header-val)))) | |
{} | |
custom-headers-def)) | |
(defn url-format [base-url path url-params] | |
;; magically returns the correct url | |
) | |
(defn build-req | |
[{:keys [api-name endpoint-name url-params custom-headers] :as _params}] | |
(let [{:keys [base-url] :as api-def} (get api-defs api-name) | |
{:keys [custom-headers-def | |
method path]} (get-in api-def [:endpoints endpoint-name]) | |
headers (construct-headers custom-headers-def custom-headers) | |
request {:url (url-format base-url path url-params) | |
:method method | |
:headers headers | |
:body "Obviously something else"}] | |
request)) | |
;; splitting the request build from request execution allows us to | |
;; validate the request built separately, without actually making it | |
(defn exec-req [request] | |
(http/request request)) | |
;; then you build a request like this | |
(let [id "<user-value>" | |
x-cb "<user-value>"] | |
(build-req | |
{:api-name :moogle | |
:endpoint-name :endpoint-a | |
:url-params {:id id} | |
:custom-headers {"X-cb-something-something" x-cb}})) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment