yonaskolb / SwagGen

OpenAPI/Swagger 3.0 Parser and Swift code generator
MIT License
625 stars 147 forks source link

Reference object isn't supported in query parameter #template #143

Closed Kastet closed 5 years ago

Kastet commented 5 years ago

Reference object isn't supported in query parameter.

parameters:
        - in: query
          name: cat
          schema:
            $ref: '#/components/schemas/Cat'

generates

public override var queryParameters: [String: Any] {
    var params: [String: Any] = [:]
    params["amount"] = options.cat.encode()
    return params
}

thought Cat will be missing encode() method.

yonaskolb commented 5 years ago

An object schema for a query param isn't support as it's unclear what the encoded string should be. What would you expect to get written?

Kastet commented 5 years ago

The convention for nested dictionary values is to use keys surrounded by square brackets. Before getting URL-encoded the query param part of the URL will look like this

cat[name]=Joe&cat[age]=5&cat[owner][id]=1

Alamofire's URLEncoding.queryString should be able to do the job (and it's already used to encode query params), in which case, all we need to do is to convert models into [String: Any]. The first thing that comes to mind is JSONSerialization.

extension Cat {
    func encode() ->  [String: Any] {
        let jsonData = try! JSONEncoder().encode(self)
        return try? JSONSerialization.jsonObject(with: jsonData) ?? [:]
    }
}

Thoughts?

yonaskolb commented 5 years ago

@Kastet I see. If you'd like to add that feature, you're more than welcome to. Our Models are already Codable, so you could hook into that. I see it as fairly edge case for a proper REST api.