Created by: allezxandre
This MR relates to issue #7549, and implements support for oneOf
in Swift. anyOf
fields remain unsupported in this PR (despite the branch name).
Given a oneOf
field named field_name
, defined as:
{
"oneOf": [
{ "$ref": "#/components/schemas/SchemaA" },
{ "$ref": "#/components/schemas/SchemaB" },
{ "$ref": "#/components/schemas/SchemaC" }
]
}
the generator will generate a model named FieldNameOneOf
to hold the values. It is an enumeration with associated values that looks like follows:
public enum FieldNameOneOf: Codable {
case typeSchemaA(SchemaA)
case typeSchemaB(SchemaB)
case typeSchemaC(SchemaC)
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
switch self {
case .typeSchemaA(let value):
try container.encode(value)
case .typeSchemaB(let value):
try container.encode(value)
case .typeSchemaC(let value):
try container.encode(value)
}
}
public init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
if let value = try? container.decode(SchemaA.self) {
self = .typeSchemaA(value)
} else if let value = try? container.decode(SchemaB.self) {
self = .typeSchemaB(value)
} else if let value = try? container.decode(SchemaC.self) {
self = .typeSchemaC(value)
} else {
throw DecodingError.typeMismatch(Self.Type.self, .init(codingPath: decoder.codingPath, debugDescription: "Unable to decode instance of FieldNameOneOf"))
}
}
}
Usage then goes along something like:
switch model.fieldName {
case .typeSchemaA(let value):
// Use `value`, an object of type SchemaA
// do something with it...
break
case .typeSchemaB(let value):
// do something else with value of type SchemaB...
break
case .typeSchemaC(let value):
// do something else with value of type SchemaC...
break
}
oneOf
s are defined by the OpenAPI spec as:
validates the value against exactly one of the subschemas
Currently, the generator does not implement validation that the value matches only one subschema, but it might be added in the future if need be.
PR checklist
-
Read the contribution guidelines. -
Pull Request title clearly describes the work in the pull request and Pull Request description provides details about how to validate the work. Missing information here may result in delayed response from the community. -
Run the following to build the project and update samples: ./mvnw clean package ./bin/generate-samples.sh ./bin/utils/export_docs_generators.sh
./bin/generate-samples.sh bin/configs/java*
. For Windows users, please run the script in Git BASH. → no change -
File the PR against the correct branch: master
,5.1.x
,6.0.x
→ I guess this is aimed at5.1.x
, but it seems 5.1 changes are integrated into master -
If your PR is targeting a particular programming language, @mention the technical committee members, so they are more likely to review the pull request — @jgavris @ehyche @Edubits @jaz-ah @4brunu