- Hands-On Server-Side Web Development with Swift
- Angus Yeung
- 157字
- 2021-06-10 19:00:25
Retrieving an entry
The handlers in the route group /journal/Int.parameter deal with a specific entry. The first handler belonging to this route group is getEntry():
func getEntry(_ req: Request) throws -> Entry {
let index = try req.parameters.next(Int.self) // [1]
let res = req.makeResponse() // [2]
guard let entry = journal.read(index: index) else {
throw Abort(.badRequest)
}
print("Read: \(entry)")
try res.content.encode(entry, as: .formData) // [3]
return entry
}
There are several interesting steps in the preceding implementation:
- Retrieve the index of an Entry object, using the req.parameters.next() command
- Create a response instance by calling the makeResponse() method
- Serialize the Entry object that conforms to Content into a JSON object and return
All handlers in this route group use the same req.parameters.next() command in [1] to work with a specific Entry object. The line at [3] demonstrates how easy it is to serialize a data model into a JSON object once the model conforms to the Content protocol.