Chapter 7: Best way to extract query params

In Chapter 7’s Fluent queriesFilter section, there is some example code:

guard let searchTerm = 
    req.query[String.self, at: "term"] else {
    throw Abort(.badRequest)
}

My question is why not simply use:

let searchTerm = try req.query.get(String.self, at: "term")

This approach also throws a 500/bad request error however the message is more descriptive:

{
    "error": true,
    "reason": "Value of type 'String' required for key 'term'."
}

Is this just an accidental oversight on the author’s part, or is there good reason to not do it this way?

2 Likes

It’s likely that req.query.get() didn’t exist when the book was originally written. It also shows you another way to write it and customise the error message etc but the newer method is probably a better way!

1 Like

Hey @0xtim thanks for your reply! I figured that was the case but didn’t want to assume. Congrats on making such a fantastic book :slight_smile: