I have an endpoint that takes an id. That id fetches something: either a Dog or a Cat; and returns it (as Pet).. It looks like this:
paths:
/getPet/{id}:
get:
operationId: getPet
parameters:
- name: id
in: query
description: id of pet
responses:
200:
description: happy
content:
application/json:
schema:
$ref: '#/components/schemas/Pet'
components:
schemas:
Pet:
type: object
required:
- petType
properties:
petType:
type: string
discriminator:
propertyName: petType
mapping:
kitty: Cat
dog: Dog
Dog:
allOf: ...
Cat:
allOf: ...
The flow looks something like this: FE requests with id -> BE fetches pet with id -> Returns the retrieved pet back via controller.
The only way I've found to create a polymorphic object is with discriminator, however it requires 2 things.. 1: A discriminator field and, 2: optionally, a mapping field.
This is how I am implementing it in my controller.. It works, but it feels very wrong what I am doing. I am not really making use of the discriminator in any way, nor the mapping I created, nor do I see a way to do so..
override fun givePets(petType: String?): ResponseEntity<Pet> {
return ResponseEntity.ok(
when (petType) {
"Dog" -> Dog("Dog", true, "Harry", 15)
"Cat" -> Cat("Cat", 27, "Smurfie", 7)
"Lizard" -> Lizard("Frog", false, "Smithers", 145)
else -> TODO()
})
}
Could someone please advise on the proper way of doing this? I find I am not understanding the OAS spec when I try and put it into practise, despite re-reading it multiple times.