Resources
Resource adds the usual JSON routes for a controller in one line. Resource(path: /people, to: people) adds these routes for the controller imported as people:
| Method | Path | Function | Name |
|---|---|---|---|
| GET | /people | index |
people.index |
| POST | /people | store |
people.store |
| GET | /people/{id} | show |
people.show |
| PUT, PATCH | /people/{id} | update |
people.update |
| DELETE | /people/{id} | destroy |
people.destroy |
A function the controller doesn't have gets no route. only: [index, show] and except: [destroy] pick the actions, name: changes the name prefix, and param: changes {id}. For example, you may put the write actions behind 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])
}
}With model:, each action asks the model's policy before the controller runs:
<!-- 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)
}| Action | Ability asked | About |
|---|---|---|
index |
None | A list has no single record. |
store |
create |
The model. |
show |
read |
The record {id} names. |
update |
update |
The same record. |
destroy |
delete |
The same record. |
A key with no record gets 404 before the policy is asked.