QueryParams
public protocol QueryParams : Decodable, Encodable
An object that conforms to QueryParams is identified as being decodable from URLEncoded data.
This can be applied to a Codable route to define the names and types of the expected query parameters, and provide type-safe access to their values. The QueryDecoder is used to decode the URL encoded parameters into an instance of the conforming type.
Usage Example:
struct Query: QueryParams {
let id: Int
}
router.get("/user") { (query: Query, respondWith: (User?, RequestError?) -> Void) in
guard let user: User = userArray[query.id] else {
return respondWith(nil, .notFound)
}
respondWith(user, nil)
}
Decoding Empty Values:
When an HTML form is sent with an empty or unchecked field, the corresponding key/value pair is sent with an empty value (i.e. &key1=&key2=).
The corresponding mapping to Swift types performed by QueryDecoder is as follows:
- Any Optional type (including
String?) defaults tonil - Non-optional
Stringsuccessfully decodes to"" - Non-optional
Booldecodes tofalse - All other non-optional types throw a decoding error
-
dateDecodingStrategyDefault implementationThe decoding strategy for Dates. The variable can be defined within your QueryParams object and tells the
QueryDecoderhow dates should be decoded. The enum used for the DateDecodingStrategy is the same one found in theJSONDecoder.Usage Example:
struct MyQuery: QueryParams { let date: Date static let dateDecodingStrategy: JSONDecoder.DateDecodingStrategy = .iso8601 static let dateEncodingStrategy: JSONEncoder.DateEncodingStrategy = .iso8601 } let queryParams = ["date": "2019-09-06T10:14:41+0000"] let query = try QueryDecoder(dictionary: queryParams).decode(MyQuery.self)Default Implementation
Default value:
Coder.defaultDateFormatterDeclaration
Swift
static var dateDecodingStrategy: JSONDecoder.DateDecodingStrategy { get } -
dateEncodingStrategyDefault implementationThe encoding strategy for Dates. The variable would be defined within your QueryParams object and tells the
QueryEncoderhow dates should be encoded. The enum used for the DateEncodingStrategy is the same one found in theJSONEncoder.### Usage Example: ###
struct MyQuery: QueryParams { let date: Date static let dateDecodingStrategy: JSONDecoder.DateDecodingStrategy = .iso8601 static let dateEncodingStrategy: JSONEncoder.DateEncodingStrategy = .iso8601 } let query = MyQuery(date: Date(timeIntervalSinceNow: 0)) let myQueryDict: [String: String] = try QueryEncoder().encode(query)Default Implementation
Default value:
Coder.defaultDateFormatterDeclaration
Swift
static var dateEncodingStrategy: JSONEncoder.DateEncodingStrategy { get }
View on GitHub
QueryParams Protocol Reference