Fork me on GitHub
#pedestal
<
2024-01-02
>
huy22:01:09

I have this code from https://www.youtube.com/@andrey.fadeev tutorial:

(def routes
  (route/expand-routes
    #{["/greet" :get respond-hello :route-name :greet]
      ["/todo/:todo-id" :get get-todo-handler :route-name :get-todo]}))
where respond-hello is a function and get-todo-handler is an interceptor. Does expand-routes accept both function and interceptor?

phill23:01:32

http://pedestal.io/pedestal/0.7-pre/guides/defining-routes.html says "The simplest route has just a URL, an HTTP verb, and a handler:

["/users" :get view-users]
"

👍 1
hlship23:01:00

A function is treated as a handler function, not an interceptor record.

hlship23:01:49

If the value after the method (:get) is a vector, then it should be a vector of interceptors. Technically, things that satisfy the IntoInterceptor protocol.

(defprotocol IntoInterceptor
  (-interceptor [t] "Given a value, produce an Interceptor Record."))

(declare interceptor)
(extend-protocol IntoInterceptor

  IPersistentMap
  (-interceptor [t] (map->Interceptor t))

  ; This is the `handler` case
  Fn
  (-interceptor [t]
    (let [int-meta (meta t)]
      ;; To some degree, support backwards compatibility
      (if (or (:interceptor int-meta)
              (:interceptorfn int-meta))
        (interceptor (t))
        (interceptor {:enter (fn [context]
                               (assoc context :response (t (:request context))))}))))

  IPersistentList
  (-interceptor [t] (interceptor (eval t)))

  Cons
  (-interceptor [t] (interceptor (eval t)))

  Symbol
  (-interceptor [t] (interceptor (resolve t)))

  Var
  (-interceptor [t] (interceptor (deref t)))

  Interceptor
  (-interceptor [t] t))

hlship23:01:36

So Maps get converted to Interceptor records.

hlship00:01:11

Functions are normally handlers, though with (not documented but in this code!) metadata, they can be functions that returns interceptors. Symbols are resolved, and Vars are de-refed. This is all still pretty static though, as the resolving/deref-ing/invoking all happens at route expansion time, thus the need for all the tricks here: http://pedestal.io/pedestal/0.7-pre/guides/live-repl.html

gratitude-thank-you 1
hlship00:01:38

I'm thinking of introducing some macros, keyed off of system properties or env vars, to make this more straight forward.

huy09:01:17

thank you very much 🙂