KScript 文档
ZH

路由与 API

资源

Resource 用一行代码为控制器添加常用的 JSON 路由。Resource(path: /people, to: people) 会为以 people 导入的控制器添加以下路由:

方法 路径 函数 名称
GET /people index people.index
POST /people store people.store
GET /people/ show people.show
PUT, PATCH /people/ update people.update
DELETE /people/ destroy people.destroy

控制器没有的函数不会生成路由。only: [index, show] 和 except: [destroy] 用于选择操作,name: 用于更改名称前缀,param: 用于更改 {id}。例如,你可以把写入类操作放在 auth 之后:

<!-- routes/api.kscript -->
<KScript.Routes>
  <import path="../controllers/people.kscript" as="people" />

  <Resource path="/people" to="people" only="index, show" />
  <Group middleware="auth">
    <Resource path="/people" to="people" only="store, update, destroy" />
  </Group>
</KScript.Routes>
// routes/api.kscript
import KScript.Http
import "../controllers/people.kscript" as people

Routes {
  Resource(path: /people, to: people, only: [index, show])
  Group(middleware: auth) {
    Resource(path: /people, to: people, only: [store, update, destroy])
  }
}

使用 model: 时,每个操作在控制器运行前都会先询问模型的 策略:

<!-- routes/api.kscript -->
<KScript.Routes>
  <import package="KScript.Auth" />
  <import path="../models/post.kscript" />
  <import path="../controllers/posts.kscript" as="posts" />

  <Resource path="/posts" to="posts" model="Post" />
</KScript.Routes>
// routes/api.kscript
import KScript.Http
import KScript.Auth
import "../models/post.kscript"
import "../controllers/posts.kscript" as posts

Routes {
  Resource(path: /posts, to: posts, model: Post)
}
操作 询问的权限 说明
index 无 列表没有单个记录。
store create 模型。
show read {id} 指定的记录。
update update 同一条记录。
destroy delete 同一条记录。

没有对应记录的键会在询问策略前返回 404。