I'm writing a web service using Vapor framework in Swift.
In my app, I have User model. The following is how I route a get request for all users.
router.get("users") { request in
return User.query(on: request).all()
}
After running the server locally, to get the users, I can make a request like localhost:8080/users
Now, I want to add parameter to the request to get users above the given age. The request will look like localhost:8080/users?above_age=25
How to add the parameter in the request using the Vapor framework? I tried with the available docs but I can't figure it.
Since I am now starting with Server Side Swift using Vapor, any reference to resources using Vapor 3 will also be of help for other issues I might face. Thanks!
The query string parameters will be in the query container and hence they can accessed like below.
router.get("users") { request -> Future<[User]> in
if let minimumAge = request.query[Int.self, at: "above_age"] {
return User.query(on: request).filter(\.age > minimumAge).all()
}
return User.query(on: request).all()
}
If the request has above_age as a query param, the router will return list of users above that age else it will return all users.