-
Notifications
You must be signed in to change notification settings - Fork 0
Handlers
Gate handlers are functions that accept a request and return something.
(defn a-handler
[request]
(let [name (get-in request [:params :name])]
(str "Hello, " name ". I am a handler.")))
Manually retrieving params from the request like in the example above means writing the same boilerplate over and over, and that's no fun. Luckily, there's a macro for that: gate/defhandler. The following example creates exactly the same handler as in the previous example.
(defhandler a-handler
[name]
(str "Hello, " name ". I am a handler."))
Another problem commonly encountered when writing handlers to is that all params are strings, even when a param represents data that isn't a string, so you often need to transform a param into the appropriate type of data before your app can use it.
In the following example, the function get-user
requires a user-id as a number. Usually you would have to call Integer/parseInt
or some similar function on your user-id param before you could pass it to get-user
, but defhandler
can make that conversion for you.
(defhandler get-user-profile
[user-id :- Number]
(let [user (get-user user-id)]
(render-profile user))
Parameters can currently be coerced from strings into Keyword
, Boolean
, Number
, Long
, Integer
, Double
, java.util.UUID
, or Edn
. If a parameter can not be coerced, it remains in its original form.
Keyword
, Boolean
, Number
, and Edn
all have behaviors that warrant an explanation.
Strings are made lower-case before being converted into keywords.
Behaves like Boolean/parseBoolean, which accepts any capitalization of "true" as true and returns false for any other string.
If the number you are trying to parse contains a decimal point, attempts to parse it as a Double. If the number you are trying to parse contains no decimal point, attempts to parse it as a Long. If the number can't be parsed as a long, attempts to read it via edn/read-string.
Will return either Double, Long, BigInt, or Ratio.
Uses edn/read-string to parse parameter.