-
Notifications
You must be signed in to change notification settings - Fork 14
How to use a controller interceptor
Added for version: 0.6
A controller interceptor can be used to intercept an incoming request to reroute, alter the request-map, or alter the response. An interceptor is simply a function which takes both the incoming request-map and the action which would be called if the request was not intercepted. The interceptor must return a response which may reroute the request to another action, or return a response.
Here is an example interceptor which simply logs “Hello World!” for every request:
(defn hello-interceptor [request-map action] (logging/debug "Hello World!") (action request-map))
Create a new conjure app called “hello_world” and add the above interceptor to the home_controller.clj file. Don’t forget to require clojure.contrib.logging in hello-controller.
Now lets make the interceptor intercept all actions in home-controller. To add an interceptor to a controller use the add-interceptor macro in conjure.controller.base. Add-interceptor can take either just the interceptor or the interceptor and parameters. Lets add the interceptor without any parameters first.
Add the following code to home-controller:
(add-interceptor hello-interceptor)
The above code adds the hello-interceptor to all actions in the hello-controller. If you restart your server and point your browser at the home page, “Hello World!” will be printed to your console.
If you try to go to /home/list_records, “Hello World!” will actually be displayed twice, once for the call to list-records and a second time for index which list-records redirected to. The same thing happens if you try to go to /home/add as well.
We could keep “Hello World!” from displaying twice if we simply exclude the list-records and add actions. To exclude list-records and add we need to pass parameters along with the interceptor. Params is a map may contain the keys :excludes, :includes and :interceptor-name. We’ll set :excludes to the set #{ :list-records, :add }.
Our new call to add-interceptor looks like:
(add-interceptor hello-interceptor { :excludes #{ :list-records, :add } })