update cn doc (#886)

This commit is contained in:
JIN 2023-08-07 12:02:20 +08:00 committed by GitHub
parent 98ef20c9d7
commit 88787856cd
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 28 additions and 21 deletions

View File

@ -25,41 +25,44 @@ struct TodosController: RouteCollection {
}
}
func index(req: Request) async throws -> String {
// ...
func index(req: Request) async throws -> [Todo] {
try await Todo.query(on: req.db).all()
}
func create(req: Request) throws -> EventLoopFuture<String> {
// ...
func create(req: Request) async throws -> Todo {
let todo = try req.content.decode(Todo.self)
try await todo.save(on: req.db)
return todo
}
func show(req: Request) throws -> String {
guard let id = req.parameters.get("id") else {
throw Abort(.internalServerError)
func show(req: Request) async throws -> Todo {
guard let todo = try await Todo.find(req.parameters.get("id"), on: req.db) else {
throw Abort(.notFound)
}
// ...
return todo
}
func update(req: Request) throws -> String {
guard let id = req.parameters.get("id") else {
throw Abort(.internalServerError)
func update(req: Request) async throws -> Todo {
guard let todo = try await Todo.find(req.parameters.get("id"), on: req.db) else {
throw Abort(.notFound)
}
// ...
let updatedTodo = try req.content.decode(Todo.self)
todo.title = updatedTodo.title
try await todo.save(on: req.db)
return todo
}
func delete(req: Request) throws -> String {
guard let id = req.parameters.get("id") else {
throw Abort(.internalServerError)
func delete(req: Request) async throws -> HTTPStatus {
guard let todo = try await Todo.find(req.parameters.get("id"), on: req.db) {
throw Abort(.notFound)
}
// ...
try await todo.delete(on: req.db)
return .ok
}
}
```
`Controller` 的方法接受 `Request` 参数,并返回 `ResponseEncodable` 对象。该方法可以是异步或者同步(或者返回一个 `EventLoopFuture`)
!!! note "注意"
[EventLoopFuture](async.md) 期望返回值为 `ResponseEncodable` (i.e, `EventLoopFuture<String>`) 或 `ResponseEncodable`.
`Controller` 的方法接受 `Request` 参数,并返回 `ResponseEncodable` 对象。该方法可以是异步或者同步。
最后,你需要在 `routes.swift` 中注册 Controller

View File

@ -527,7 +527,7 @@ Planet.find(req.parameters.get("id"), on: database)
如果没有找到具有该标识符的模型,则返回 `nil`
## 生命周期
## 生命周期(Lifecycle)
模型中间件允许你监听模型的生命周期事件。支持以下生命周期事件。

View File

@ -326,6 +326,10 @@ extension User {
app.migrations.add(User.Migration())
```
!!! tip "建议"
由于电子邮件地址是不区分大小写的,你可能希望在将其保存到数据库之前添加一个[`中间件`](../fluent/model.md#lifecycle),将电子邮件地址强制转换为小写。但是要注意,`ModelAuthenticatable` 使用区分大小写的比较,如果你这样做的话,你需要确保用户的输入都是小写,要么在客户端使用大小写强制转换,要么使用自定义身份验证器。
首先需要一个端点来创建新用户。让我们使用 `POST /users`。创建一个 [Content](../basics/content.zh.md) 的结构体,表示这个端点期望的数据。
```swift