Skip to content

Commit

Permalink
Add and update controllers section (#877)
Browse files Browse the repository at this point in the history
  • Loading branch information
ptoffy authored Aug 3, 2023
1 parent cd6da44 commit 3faa202
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 20 deletions.
42 changes: 23 additions & 19 deletions docs/basics/controllers.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,41 +24,45 @@ 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 methods should always accept a `Request` and return something `ResponseEncodable`. This method can be asynchronous or synchronous (or return an `EventLoopFuture`)
Controller methods should always accept a `Request` and return something `ResponseEncodable`. This method can be asynchronous or synchronous.

!!! note
[EventLoopFuture](async.md) whose expectation is `ResponseEncodable` (i.e, `EventLoopFuture<String>`) is also `ResponseEncodable`.

Finally you need to register the controller in `routes.swift`:

Expand Down
2 changes: 1 addition & 1 deletion mkdocs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -478,7 +478,7 @@ nav:
- Routing: "basics/routing.md"
# TODO: Improve quality
# Mostly just a code sample with little explanation.
# - Controllers: "controllers.md"
- Controllers: "basics/controllers.md"
- Content: "basics/content.md"
- Client: "basics/client.md"
- Validation: "basics/validation.md"
Expand Down

0 comments on commit 3faa202

Please sign in to comment.