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:

  1. Retrieve the index of an Entry object, using the req.parameters.next() command
  2. Create a response instance by calling the makeResponse() method
  3. 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.