Last active
February 24, 2023 02:05
-
-
Save kidpollo/e309c1eb47d859f1975263d097aa9185 to your computer and use it in GitHub Desktop.
NBB + Ruuter + Axios Lambda API proxy
This file contains hidden or 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 foo | |
{:clj-kondo/config '{:lint-as {promesa.core/let clojure.core/let | |
applied-science.js-interop/defn clojure.core/defn}}} | |
(:require [cljs-bean.core :refer [->clj ->js]] | |
[ruuter.core :as ruuter] | |
["axios$default" :as axios] | |
[clojure.string :as string] | |
[promesa.core :as p] | |
[applied-science.js-interop :as j])) | |
(def base-url "https://") | |
(def key-id "") | |
(def key-pass "") | |
(defn handle-token [_request] | |
(axios/request | |
(->js {:url "/api/token/" | |
:baseURL base-url | |
:headers {"Content-ype" "application/json"} | |
:method "post" | |
:data {:id key-id | |
:password key-pass | |
:scopes "foo,bar"}}))) | |
(defn handle-other [request] | |
{:status 200 | |
:body (str "Hello, " (:who (:params request)))}) | |
(def routes [{:path "/proxy/api/token/*" | |
:method :post | |
:response handle-token} | |
{:path "/proxy/api/*" | |
:method :any | |
:response handle-other}]) | |
(defn ->method [m] | |
(-> m string/lower-case keyword)) | |
(j/defn event->req [^js {:keys [body] {{:keys [path method]} :http} :requestContext}] | |
{:uri path | |
:request-method (->method method) | |
:data body}) | |
(j/defn response->lambda-response | |
[^js {:keys [status data]}] | |
#js {:statusCode status | |
:body data}) | |
(defn axios->lambda-response [prom] | |
(-> prom | |
(p/then | |
(fn [res] | |
(response->lambda-response res))) | |
(p/catch | |
(fn [error] | |
(->js | |
{:statusCode "500" | |
:body (.toJSON error)}))))) | |
(defn ruuter-response->lambda-response [maybe-promise] | |
(if (p/promise? maybe-promise) | |
(axios->lambda-response maybe-promise) | |
;; This is a ruuter response which isnt a promise | |
#js {:statusCode (:status maybe-promise) :body (:body maybe-promise)})) | |
(defn handler [event _ctx] | |
(let [request (event->req event)] | |
(-> routes | |
(ruuter/route request) | |
ruuter-response->lambda-response))) | |
#js {:handler handler} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment