컨트롤러
컨트롤러 작성하기
컨트롤러는 일반 fn이며, 보통 라우트 파일이 가져오는 자체 스크립트에 있어요. 응답이 어떠해야 하는지를 반환해요:
<!-- 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)
}
}컨트롤러가 받는 값
컨트롤러의 매개변수는 이름으로 채워져요. 필요한 것만 요청하세요:
| 매개변수 | 보관하는 내용 |
|---|---|
경로 매개변수, 예를 들어 id |
경로에서 온 값이에요: {id}은 $id가 돼요. |
request |
페이지 요청 필드이며, scheme와 url를 포함해요. 일치한 라우트는 ip, json, input, route도 주고 (이름, 또는 null), 요청을 참고하세요. |
json |
본문을 JSON으로 읽은 값이며, JSON이 아니면 null예요. |
body |
JSON이 있으면 그 JSON을, 없으면 원시 텍스트를 줘요. |
input |
쿼리, 폼, JSON 필드를 한데 합친 값이에요. |
query, form, headers, cookies |
요청의 각 부분을 따로 준 값이에요. |
files |
입력 이름별로 정리된 업로드된 파일이에요. |
타입이 지정된 입력
타입이 지정된 매개변수는 자동으로 변환돼요. 그래서 id: int는 숫자가 돼요. 숫자는 맞추려고 반올림하지 않아요: 1.9는 int에 대해, 또는 담을 수 없을 만큼 큰 숫자는 422(경로에서는 404)를 내고, 2와 2.0은 둘 다 2예요.
type은 요청 데이터를 레코드로 매핑하므로, 컨트롤러는 항상 올바른 모양의 데이터만 받아요:
<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
// …
}형식이 맞지 않는 데이터는 클라이언트의 실수이므로 컨트롤러가 실행되지 않아요. 형식이 맞지 않는 본문, 쿼리 또는 폼은 422 Unprocessable Entity을 받고, API 라우트는 모든 문제를 나열한 JSON으로 응답해요:
{ "error": "...", "status": 422, "problems": [{ "path": "$.age", "field": "age", "message": "..." }] }형식이 맞지 않는 경로 매개변수, 예를 들어 id: int에 대한 /people/abc은 404을 받아요.
업로드된 파일
multipart/form-data으로 전송된 폼은 텍스트 필드를 form에, 파일을 files에 담아요. 하나의 입력이 여러 파일을 보낼 수 있으므로 각 입력 이름은 목록을 담아요. 파일에는 name, type, 바이트 단위의 size, 그리고 base64 값으로서의 bytes가 있어요. 이는 실시간 컴포넌트의 $event.files와 같은 모양이에요:
<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')
}파일 이름과 타입은 브라우저가 알려준 값이므로, 신뢰하기 전에 내용을 확인하고 저장할 이름은 직접 정하세요. 한 요청의 파일은 모두 합쳐 8 MiB까지일 수 있어요. kscript.json의 http.upload_limit로 이를 바꿀 수 있고, 더 큰 요청은 413으로 응답돼요. $request.files도 같은 맵을 담으며, 비어 있는 파일 입력은 아무것도 보내지 않아요.
라우트 모델 바인딩
KScript.Data 모델로 타입이 지정된 경로 매개변수는 그 키를 가진 레코드가 되므로, 컨트롤러는 게시물 자체를 받아요. 레코드가 없는 키나 키가 아닌 값은 404을 받고, API 문서에서 키의 타입을 보여줘요:
<!-- 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) => $post라우트가 실행하는 어떤 코드든 @inject()로 그 레코드를 요청할 수 있으므로 값을 일일이 넘겨줄 필요가 없어요. 컨트롤러가 호출하는 함수는 모델의 이름을 적어요:
<fn name="word_count" value="@inject(Post).body->split(' ')->count()" />fn word_count() => @inject(Post).body->split(' ')->count()컴포넌트는 이를 입력의 기본값으로 받으므로, 뷰의 <post-card />에는 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()은 입력 이름과 같은 경로 매개변수(post의 경우 {post})를 찾고, 그다음 그 모델의 라우트 레코드 하나를 찾아요. 매개변수 이름을 직접 정하고 싶다면 @inject(from: article)라고 쓸 수 있어요.
view:로 응답된 라우트는 키만 가지므로, 레코드는 처음 요청될 때 찾아지고, 레코드가 없는 키는 거기서도 404을 받아요. 모델의 레코드가 없는 라우트, 예를 들어 id: int가 없는 /posts/{id}는 오류이며, 하나를 넘기라고 알려줘요: Post->find($id).
라우트 권한 부여
라우트는 컨트롤러가 실행되기 전에 모델의 정책에 물어볼 수 있어요. can: update은 컨트롤러의 타입이 지정된 경로 매개변수가 가리키는 레코드 하나에 대해 묻고, 정책이 거부하면 403를 답해요:
<!-- 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)
}능력이 거부한 손님은 로그인하라는 안내를 받거나, API 라우트에서는 401을 받아요. 레코드를 두 개 가진 라우트는 어느 것을 뜻하는지 알 수 없으므로, 컨트롤러가 의도한 레코드에 대해 @authorize(update, $post)를 호출해요. view:로 응답된 라우트에는 레코드의 타입을 정해줄 컨트롤러가 없으므로, 그 컴포넌트들은 @inject(can: read)로 묻어요.
응답 반환하기
컨트롤러가 반환한 값이 응답이 돼요:
| 반환값 | 응답 |
|---|---|
| 맵, 목록, 숫자 또는 참/거짓 | JSON(application/json). |
| Text | HTML. |
@view('people/show', person: $p) |
레이아웃과 함께 렌더링된 뷰예요. status:은 상태를 정해요: @view('auth/login', data: { error: $err.message }, status: 429). |
@response(body, status: 201, type: 'text/csv', headers: { … }) |
직접 정한 상태, 타입, 헤더예요. 맵 또는 목록 본문은 JSON이 돼요. |
@redirect(/people), @redirect(to: '/new', status: 301) |
리디렉션. |
@redirect_back('/people') |
요청이 온 페이지로의 리디렉션이며, Referer이 없거나 다른 사이트의 것이면 기본 페이지로 가요. |
없음(null) |
204 No Content. |
상태나 헤더를 직접 지정해야 할 때는 @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) })
}
}@response(@read_bytes(./logo.png), type: 'image/png')와 같은 base64 본문은 원래의 바이트를 그대로 보내요. 별도로 지정하지 않으면 콘텐츠 타입은 application/octet-stream이에요.
요청을 어디서든 멈추려면 @abort()을 호출하세요: @abort(404) 또는 @abort(403, message: 'Admins only'). 컨트롤러, 그것이 호출하는 함수, 또는 미들웨어에서 동작하며, try는 이를 잡지 않아요.
@view()로 렌더링된 뷰의 컨트롤러와 액션은 사이트 폴더 안의 파일을 읽고 쓸 수 있어요. 둘 다 읽기 전용으로 만들려면 "write_files": false를 설정하세요. 컨트롤러가 echo로 출력한 내용은 서버 로그로 가요.
오류와 상태 코드
오류 타입은 상태를 담을 수 있어요. 컨트롤러 또는 그것이 호출한 것이 이를 던지고 아무것도 잡지 않으면, 요청은 그 상태와 오류 메시지로 응답되며, 파일과 줄 번호는 빠져요. API 라우트는 오류의 타입과 필드를 담은 JSON으로 응답해요:
<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
}이 오류 타입들은 기본으로 내장되어 있으므로 throw Forbidden "Admins only"은 선언 없이도 동작하고, 이를 확장한 오류 타입은 그 상태로 응답해요:
| 오류 타입 | 상태 |
|---|---|
BadRequest |
400 |
Unauthorized |
401 |
Forbidden |
403 |
NotFound |
404 |
Conflict |
409 |
Validation |
422 |
TooManyRequests |
429, 오류에 retry_after 필드가 있으면 Retry-After과 함께 |
error PaymentFailed(status: 402)으로 오류 타입에 고유한 상태를 줄 수 있어요. @abort()와 달리 이들은 일반 오류이므로, 컨트롤러의 try가 여전히 이를 잡을 수 있어요. 상태가 없는 오류는 파일과 줄 번호와 함께 500로 응답해요.
사이트를 작업하는 동안 500에는 오류 메시지, 파일, 줄 번호가 표시되며, API 경로에서는 JSON으로 출력되고 서버 로그에도 기록됩니다. 프로덕션 환경(kscript serve --env production 또는 KSCRIPT_ENV=production)에서는 응답으로 Something went wrong on our side. Please try again later.만 보이며, 자세한 내용은 서버 로그에 기록됩니다. 자체 상태 코드가 있는 오류와 @abort()는 두 환경 모두에서 같은 방식으로 응답합니다.
요청 본문을 읽을 수 없을 때, 크기나 필드 한도를 넘으면 413로, 본문이 중간에 잘렸거나 Content-Type와 일치하지 않으면 400로 응답합니다. API 경로에서는 JSON으로 응답합니다.