Make model-schema capture element addition on an array field request

265 views Asked by At

I am doing an adapter for a REST API. I've used model schema for the POST and PUT method's body. @RequestBody Model1 requestBody at the adapter.

Now, I encountered body with fields that requires an array.

Swagger UI body input

Time 1 ) On Swagger load, Model-initiated :

{
    "field1"         : "",
    "field2Optional" : "",
    "fieldArray"     : [
        { "field2a"                  :  "input2a" }
    ]

}

Time 2 ) User-edited :

{
    "field1"         : "input1",
    "field2Optional" : "",
    "fieldArray"     : [
        { "field2"        :  "input2a" },
        { "field2"        :  "input2b-userAddition " }
    ]
}

Model1.groovy

@XmlElement
String field1 = ''

@XmlElement
String fieldOptional = ''

@XmlElement
ArrayList<Model2> fieldArray = new ArrayList<>( Arrays.asList(new Model2()) ).get(0)

}

Model2.groovy

@XmlElement
String field2 = ''

I want Model1 to capture/save the elements the user added to the fieldArray like, { "field2" : "input2b-userAddition " }. With the current code, I can only get the first element of the array get(0), I don't want to create many instance of Model2 unless the user said so.

The solution I have in mind is to use @RequestBody Map requestBody inside Model1.groovy to get the whole body request and compare the actual user input vs the model. Then add the fields not found in the model but found in the actual user input. I wonder if there is a better way to do this?

1

There are 1 answers

0
Himanshu Mishra On

Using @RequestBody Map requestBody inside Model1.groovy to get the whole body request and compare the actual user input vs the model seems a very nice and clean idea to me. I believe there can't be a better way.