-
Notifications
You must be signed in to change notification settings - Fork 38
Middleware
Blackfish is essentially routing and middleware web framework that has minimal functionality of its own: A Blackfish application is essentially a series of middleware function calls.
Middleware functions are functions that have access to the request object (request
), the response object (response
), and the next middleware function in the application’s request-response cycle. The next middleware function is commonly denoted by a variable named next
.
Middleware functions can perform the following tasks:
- Execute any code.
- Make changes to the request and the response objects.
- End the request-response cycle.
- Call the next middleware function in the stack.
If the current middleware function does not end the request-response cycle, it must call next()
to pass control to the next middleware function. Otherwise, the request will be left hanging.
A Blackfish application can use the following types of middleware:
- Application-level middleware
- Router-level middleware
- Error-handling middleware (Coming Soon)
- Built-in middleware
- Third-party middleware
You can load application-level and router-level middleware with an optional mount path. You can also load a series of middleware functions together, which creates a sub-stack of the middleware system at a mount point.
Bind application-level middleware to an instance of the app object by using the app.use(middleware: )
and app.METHOD()
functions, where METHOD
is the HTTP method of the request that the middleware function handles (such as GET, PUT, or POST) in lowercase.
This example shows a middleware function with no mount path. The function is executed every time the app receives a request.
import Blackfish
let app = Blackfish()
app.use { request, response, next in
print("Time: \(NSDate())")
next()
}