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 to nil
  • Non-optional String successfully decodes to ""
  • Non-optional Bool decodes to false
  • All other non-optional types throw a decoding error
  • dateDecodingStrategy Default implementation

    The decoding strategy for Dates. The variable can be defined within your QueryParams object and tells the QueryDecoder how dates should be decoded. The enum used for the DateDecodingStrategy is the same one found in the JSONDecoder.

    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.defaultDateFormatter

    Declaration

    Swift

    static var dateDecodingStrategy: JSONDecoder.DateDecodingStrategy { get }
  • dateEncodingStrategy Default implementation

    The encoding strategy for Dates. The variable would be defined within your QueryParams object and tells the QueryEncoder how dates should be encoded. The enum used for the DateEncodingStrategy is the same one found in the JSONEncoder.

    ### 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.defaultDateFormatter

    Declaration

    Swift

    static var dateEncodingStrategy: JSONEncoder.DateEncodingStrategy { get }