In this chapter, I introduce you new term -- Middleware. This is the most important concept to know why Clack is so powerful and extensible without losing simplicity.
What's Middleware?
Until now, an Application takes Request and just returns Response.
I add Middlewares to this figure.
Middlewares are surrounding an Application. It takes a Request before Application takes it and gets the Response which Application generates. By wrapping an Application, Middleware allows you to change the Application behaviour without rewriting the existing code.
This is a mechanism full of possibility very much.
Clack.Middleware
Writing Middleware of Clack isn't so difficult for you who already know Component.
;; importing symbols for readability.
(import '(clack:<middleware>
clack:call
clack:call-next))
(defclass <sample-mw> (<middleware>) ())
(defmethod call ((this <sample-mw>) env)
;; preprocessing
(let ((response (call-next this env)))
;; postprocessing
))
Clack Middleware is a subclass of <middleware>. It also has a method call. It is really similar to <component>.
Did you notice a function call-next? It means calling "the next" Component, Middleware or Application. Remember the second figure in this page. Middlewares wrap another Component. By calling call-next, Middlewares can call another wrapped Component.
The beauty of Middleware is that it can be reused between Web applications. In the next chapter, I'll introduce you the real example of Middleware.