Bwf/ GuideFrançais
Bwf Guide

Controllers and typed responses

We’ll start with a health check. When a client asks whether the Journal is running, our action only needs to send back the word “ok”.

The action belongs to an operation

First find the health operation in the OpenAPI file. Its declaration tells Bend what the action will receive and which responses it can send. A health check can take the application configuration alone. Later, when we write an action for a signed-in reader, the signature will give us their account as well.

IHP controllers

Read the generated signature

Start by reading the return type on the action below. The word “ok” is the body of the 200 response declared for the health operation. This action only takes the configuration. For another op, Api.Handler(op) picks up that operation’s context, path arguments, query, body and return type.

def action(config: Controller.Config) -> IO(Api.HealthResponse):
  IO.pure(Api.HealthResponse, Api.Health200{"ok"})

Add the action to the route table

Having written the action, we still need to tell the router where to find it. Look for the Api.OnHealth{} case in handler below. Its right-hand side is our function. Mount the closed template with Api.mount(~handler). When you add a second operation to the YAML, add a case for it here too.

def handler(op: Api.Operation) -> Api.Handler(op):
  match op:
    case Api.OnHealth{}: HealthCheck.action

Send HTML, JSON or a redirect

For a page, supply a title and an Html.Html body to the layout. A fragment can carry just the HTML going into the target. For JSON, build the value declared for the response. A 303 takes a GET destination with the right arguments.

After saving an article, the Journal sends a 303 to the article’s GET with the slug returned by the insert.

Api.ArticleWrite303{Contract.To{Api.target_article(slug)}}

Use the account from the context

The router decodes the request and hands the action its access context. With Controller.SignedIn, the action already has an account. Whether that account may change the article is an application rule.

Read the account ID from the context before calling the query that checks ownership.

user_id = Controller.signed_in_user(context)

Try it in the Journal

Publish and edit an article