Routing
Handling Requests
When a request comes through the host & port on which your server is listening, it immediately gets routed to your application You can set up handlers in your application’s boot()
function.
Handlers are defined with the .on(method:at:handler:)
function, which takes an HTTPMethod
, a path, and a handler. The handler is a closure that accepts a Request
and returns a type that conforms to ResponseConvertable
.
There’s sugar for registering handlers for specific methods via get()
, post()
, put()
, patch()
, etc.
Returning a Value
Handlers can be asynchronous and throw errors. They should return either a Response
, something conforming to ResponseConvertible
, something conforming to Encodable
, or Void
.
Response
ResponseConvertible
Encodable
Void
Chaining Requests
To keep code clean, handlers are chainable.
Error Handling
If a handler throws an error, it will be caught & automatically mapped to a Response
.
Generic errors will result in an Response
with a status code of 500, but if any error that conforms to ResponseConvertible
is thrown, it will be converted as such.
Out of the box, Alchemy provides HTTPError
which conforms to ResponseConvertible
. If it is thrown, the response will contain the status code & message of the error.
Custom Default Error Handler
By default, unhandled errors will result in a 500 response. If you’d prefer, you can use setErrorHandler
to return a custom Response
whenever your app encounters an unhandled error.
Custom Not Found Handler
Likewise, use notFoundHandler
to return a custom Response
when a request is made that doesn’t match any of your app’s routes.
Route Parameters
Dynamic route parameters can be added with a variable name prefaced by a colon (:
). The value of the parameter can be accessed on the Request
object.
As long as they have different names, a route can have as many path parameters as you’d like.
Route Groups
You can use .group()
to add middleware or path prefixes to a specific group of routes.
There is also a closure based .group()
that will isolate the prefix or middleware to any handlers defined in the closure. Using the closure based version, the example above would look like so:
Route Streaming
By default, Alchemy collects the entire body of a Request
before a route handler is called. If the request is uploading a large file, this could balloon memory. If you’d like to enable request streaming, pass the .stream
to a handler’s options
parameter. This will call the handler as soon as the request’s body begins streaming so you can handle each chunk as it comes in.