Controllers
Writing a controller
A controller is a plain fn, usually in a script of its own that the route file imports. It returns what the response should be:
<!-- controllers/people.kscript -->
<kscript>
<import package="KScript.IO" />
<import package="KScript.Http" />
<fn name="all" value="@read_json(./data/people.json)" />
<fn name="find" params="id: int" value="@all()->find(fn(p) => $p.id == $id)" />
<fn name="index" params="query: map">
<!-- GET /api/people?role=Founder -->
<return value="@all() |> filter(fn(p) => $query.role == null or $p.role == $query.role)" />
</fn>
<fn name="page" params="id: int">
<!-- GET /people/2 -->
<let name="person" value="@find($id) ?? @abort(404, message: 'Nobody has that id.')" />
<return value="@view('people/show', person: $person)" />
</fn>
</kscript>// controllers/people.kscript
kscript {
import KScript.IO
import KScript.Http
fn all() => @read_json(./data/people.json)
fn find(id: int) => @all()->find(fn(p) => $p.id == $id)
fn index(query: map) {
// GET /api/people?role=Founder
return @all() |> filter(fn(p) => $query.role == null or $p.role == $query.role)
}
fn page(id: int) {
// GET /people/2
$person = @find($id) ?? @abort(404, message: 'Nobody has that id.')
return @view('people/show', person: $person)
}
}What a controller is given
A controller's parameters are filled in by name. Ask only for what it needs:
| Parameter | What it holds |
|---|---|
a path parameter, such as id |
The value from the path: {id} becomes $id. |
request |
The page request fields, including scheme and url. A matched route also gives ip, json, input and route (its name, or null). See The request. |
json |
The body read as JSON, or null if it wasn't JSON. |
body |
The JSON if there was any, otherwise the raw text. |
input |
The query, form and JSON fields together. |
query, form, headers, cookies |
Each part of the request on its own. |
files |
The uploaded files, by input name. |
Typed input
A typed parameter is converted for you, so id: int gives a number. Numbers aren't rounded to fit: 1.9 for an int, or a number too large to hold, answers 422 (or 404 in the path), while 2 and 2.0 are both 2.
A type maps the request's data into a record, so the controller only ever sees data of the right shape:
<type name="NewPerson">
<field name="name" type="string" />
<field name="age?" type="int" />
<field name="role?" type="string" />
</type>
<fn name="store" params="json: NewPerson">
<!--
$json is a NewPerson record
…
-->
</fn>type NewPerson {
name: string
age?: int
role?: string
}
fn store(json: NewPerson) {
// $json is a NewPerson record
// …
}Data that doesn't fit is the client's mistake, so the controller doesn't run. A body, query or form that doesn't fit gets 422 Unprocessable Entity, and API routes answer with JSON that lists every problem:
{ "error": "...", "status": 422, "problems": [{ "path": "$.age", "field": "age", "message": "..." }] }A path parameter that doesn't fit, such as /people/abc for id: int, gets 404.
Uploaded files
A form posted as multipart/form-data puts its text fields in form and its files in files. Each input name holds a list, because one input can send several files. A file has a name, a type, a size in bytes and its bytes as a base64 value, the same shape a live component's $event.files has:
<form method="post" action="/avatar" enctype="multipart/form-data">
<input type="file" name="avatar">
<button>Upload</button>
</form><import package="KScript.Http" />
<import package="KScript.Storage" />
<fn name="store" params="files: map">
<let name="avatar" value="($files.avatar ?? [])->first() ?? @abort(422, message: 'Choose a picture.')" />
<if !$avatar.type->starts_with('image/')>
<return value="@redirect_back('/profile')" />
</if>
<do>@storage(data)->write_bytes("avatars/{ @uuid() }.png", $avatar.bytes)</do>
<return value="@redirect('/profile')" />
</fn>import KScript.Http
import KScript.Storage
fn store(files: map) {
$avatar = ($files.avatar ?? [])->first() ?? @abort(422, message: 'Choose a picture.')
if !$avatar.type->starts_with('image/') => return @redirect_back('/profile')
@storage(data)->write_bytes("avatars/{ @uuid() }.png", $avatar.bytes)
return @redirect('/profile')
}The file's name and type are what the browser said, so check the content before trusting them, and choose the saved name yourself. The files of one request may be 8 MiB in all; http.upload_limit in kscript.json changes that, and a bigger request is answered 413. $request.files holds the same map, and an empty file input sends nothing.
Route model binding
A path parameter typed as a KScript.Data model is the record with that key, so the controller gets the post itself. A key with no record, or one that isn't a key, gets 404, and the API docs show the key's type:
<!-- routes: Get(path: /posts/{post}, to: @posts.show) -->
<fn name="show" params="post: Post" value="$post" />// routes: Get(path: /posts/{post}, to: @posts.show)
fn show(post: Post) => $postAnything the route runs may ask for that record with @inject(), so it doesn't have to be handed down. A function the controller calls names the model:
<fn name="word_count" value="@inject(Post).body->split(' ')->count()" />fn word_count() => @inject(Post).body->split(' ')->count()A component takes it as an input's default, so <post-card /> in the view needs no post="...":
<!-- _components/post-card.kscript -->
<import package="KScript.Web" />
<import path="../models/post.kscript" />
<type name="PostCard" extends="Component">
<construct>
<field name="post" type="Post" default="@inject()" />
</construct>
<fn name="render" value="```html
<h2>{$post.title}</h2>
```" />
</type>// _components/post-card.kscript
import KScript.Web
import "../models/post.kscript"
type PostCard extends Component {
construct({ post: Post = @inject() })
fn render() => ```html
<h2>{$post.title}</h2>
```
}@inject() looks for the path parameter with the input's name ({post} for post), then for the route's one record of that model. If you would like to name the parameter yourself, you may write @inject(from: article).
A route answered with view: has only the key, so the record is found when it is first asked for, and a key with no record gets 404 there too. A route with no record of the model, such as /posts/{id} with id: int, is an error that tells you to pass one: Post->find($id).
Authorizing a route
A route may ask the model's policy before its controller runs. can: update asks about the one record that the controller's typed path parameters name, and answers 403 when the policy says no:
<!-- routes/api.kscript -->
<KScript.Routes>
<import package="KScript.Auth" />
<import path="../models/post.kscript" />
<import path="../controllers/posts.kscript" as="posts" />
<Put path="/posts/{post}" to="posts.update" can="update" />
</KScript.Routes>// routes/api.kscript
import KScript.Http
import KScript.Auth
import "../models/post.kscript"
import "../controllers/posts.kscript" as posts
Routes {
Put(path: /posts/{post}, to: @posts.update, can: update)
}A guest the ability turns away is sent to sign in, or gets 401 on an API route. A route that holds two records can't tell which one is meant, so its controller calls @authorize(update, $post) for the one it means. A route answered with view: has no controller to type the record, so its components ask with @inject(can: read).
Returning a response
What a controller returns becomes the response:
| Return | Response |
|---|---|
| A map, list, number or true/false | JSON (application/json). |
| Text | HTML. |
@view('people/show', person: $p) |
The view, rendered with its layout. status: sets the status: @view('auth/login', data: { error: $err.message }, status: 429). |
@response(body, status: 201, type: 'text/csv', headers: { … }) |
Your own status, type and headers. A map or list body is JSON. |
@redirect(/people), @redirect(to: '/new', status: 301) |
A redirect. |
@redirect_back('/people') |
A redirect to the page the request came from, or to the default when the Referer is missing or another site's. |
nothing (null) |
204 No Content. |
When you need a status or headers of your own, return @response():
<!-- controllers/people.kscript -->
<kscript>
<import package="KScript.Http" />
<type name="NewPerson">
<field name="name" type="string" />
<field name="age?" type="int" />
<field name="role?" type="string" />
</type>
<fn name="store" params="json: NewPerson">
<!-- POST /api/people -->
<if $json.name->trim() == ''>
<return value="@response({ error: 'A person needs a name.' }, status: 422)" />
</if>
<let name="person" value="{ id: 3, name: $json.name }" />
<return value="@response($person, status: 201, headers: { Location: @route('people.show', id: $person.id) })" />
</fn>
</kscript>// controllers/people.kscript
kscript {
import KScript.Http
type NewPerson {
name: string
age?: int
role?: string
}
fn store(json: NewPerson) {
// POST /api/people
if $json.name->trim() == '' {
return @response({ error: 'A person needs a name.' }, status: 422)
}
$person = { id: 3, name: $json.name }
return @response($person, status: 201, headers: { Location: @route('people.show', id: $person.id) })
}
}A base64 body, such as @response(@read_bytes(./logo.png), type: 'image/png'), sends the original bytes. Its content type is application/octet-stream unless you give one.
To stop a request from anywhere, call @abort(): @abort(404) or @abort(403, message: 'Admins only'). It works in a controller, a function it calls, or middleware, and try doesn't catch it.
Controllers, and actions in views rendered with @view(), may read and write files within the site folder. Set "write_files": false to make both read-only. Anything a controller prints with echo goes to the server log.
Errors and status codes
An error type can carry a status. When a controller, or anything it calls, throws one and nothing catches it, the request is answered with that status and the error's message, without the file and line. API routes answer with JSON that has the error's type and fields as well:
<error name="PersonNotFound" message="No person with id {$id}" extends="NotFound">
<field name="id" type="int" />
</error>
<let name="people" value="{ 1: { name: 'Ada' } }" />
<fn name="show" params="id: int">
<let name="person" value="$people[$id]" />
<if $person == null>
<throw value="PersonNotFound(id: $id)" /> <!-- GET /api/people/7 answers 404: { "error": "No person with id 7", "status": 404, "type": "PersonNotFound", "id": 7 } -->
</if>
<return value="$person" />
</fn>error PersonNotFound(message: "No person with id {$id}") extends NotFound {
id: int
}
$people = { 1: { name: 'Ada' } }
fn show(id: int) {
$person = $people[$id]
if $person == null {
throw PersonNotFound(id: $id) // GET /api/people/7 answers 404: { "error": "No person with id 7", "status": 404, "type": "PersonNotFound", "id": 7 }
}
return $person
}These error types are built in, so throw Forbidden "Admins only" works without a declaration, and an error type that extends one answers with its status:
| Error type | Status |
|---|---|
BadRequest |
400 |
Unauthorized |
401 |
Forbidden |
403 |
NotFound |
404 |
Conflict |
409 |
Validation |
422 |
TooManyRequests |
429, with Retry-After when the error has a retry_after field |
Give an error type a status of its own with error PaymentFailed(status: 402). Unlike @abort(), these are ordinary errors, so a try in the controller can still catch them. An error without a status answers 500, with the file and line.
While you work on a site, a 500 shows the error's message, file and line, as JSON on API routes, and the server log shows it too. In production (kscript serve --env production, or KSCRIPT_ENV=production) the answer is only Something went wrong on our side. Please try again later., and the details go to the server's log. Errors with a status of their own, and @abort(), say the same in both.
A request whose body can't be read answers 413 when it is over a size or field limit, and 400 when it is cut short or isn't what its Content-Type says, as JSON on API paths.