Filters and Halting
Filters are Rails' before_action, written as plain functions. Halt answers a request early from anywhere under an action.
Filters
A filter is a function
Conn -> Result<Response, Conn>.
Ok(conn) lets the request through, with a possibly
changed conn. Err(response) stops it and sends that
response.
Action.before(filters, action) returns a new action
that runs the filters in order, then the action. The first
Err wins, and nothing after it runs.
module StatsController
uses
Std.{Http, List, Option, Result}
Layout
Models.Article
Ticket.{Action, Conn, Params, Response}
Views.Admin
functions
show(conn: Conn) -> Response / {Mut} {
Action.before([require_token], stats)(conn)
}
stats(conn: Conn) -> Response / {Mut} {
Response.render(Layout.app("Stats", Admin.stats(List.length(Article.all()))))
}
/// Halts with 401 unless `?token=secret`.
require_token(conn: Conn) -> Result<Response, Conn> {
if Params.string(conn, "token") == Some("secret") {
Ok(conn)
} else {
Err(Response.text(401, "unauthorized"))
}
}
exports
show
GET /admin/stats -> 401 "unauthorized"
GET /admin/stats?token=secret -> 200 <dl><dt>Articles</dt><dd>1</dd></dl>
Filters and the action can use effects, and
before keeps them in its result.
Note: Action.Filter names
the pure filter type. A value annotated Filter can't
go in a list with effectful filters, so pass filters by name
instead. This goes away once Polar supports effect rows in type
aliases.
Halting
Sometimes the reason to stop is deep in a helper, like a record that
doesn't exist. throw Halt(response) from
Ticket.Error answers with response,
however deep the call. The router catches it.
/// The article `:id` names, or a 404 from wherever this is called.
find_or_halt(conn: Conn) -> Article / {Mut, Throws<Halt>} {
match Option.and_then(Params.id(conn, "id"), Article.find) {
Some(article) -> article,
None -> throw Halt(Response.not_found()),
}
}
The Throws<Halt> in the signature is how you know
a function might end the request.