Body Tranform - scalable solution for continuously growing API

Hello Tyk team,

I started to play with the body transform tester, and noticed that if a field is not included in the template, the result of the JSON will exclude this field. This solution is scalable, cause if we continue to add field in our API object, we will have to maintain the template continuously. It’s a big overhead.
Do you have a solution for that?

Another question, I would like to make a transformation of the inner response according the example:
We would like to change the field ‘name’ to another value in the ‘result’ array, do you have a simple example of code that can enable that?

{
“metadata”: {
“total”: 2
},
“debug”: “6715f2c3-9a5a-4aaa-bb4c-f51d179eb9b5”,
“error”: null,
“result”: [
{
“type”: “User”,
“id”: 1073741831,
“name”: null
},
{
“type”: “User”,
“id”: 1073741832,
“name”: null
}
]
}

Thank you,
Johana

Regarding new fields. Well, if you have nested object which not gets changed, you can copy it to the template as it is, using {{jsonMarshal .nested}} pattern.

Regarding additional fields, it can be solved like this:
Let’s say we have original data like this {"a": 1, "b": "c", "d": true}, and we want to keep all fields, but rename “a” to “new”. It can be achieved with following template:

{
{{range $k, $v := .}}
    {{if eq $k "a"}}
    "new": {{jsonMarshal $v}},
    {{else}}
    "{{$k}}": {{jsonMarshal $v}},
    {{end}}
{{end}}
"ok": 1
}

Which will output: { "new": 1, "b": "c", "d": true, "ok": 1 }.

Note that I use jsonMarshal to properly output JSON type, so it will wrap strings to quotes, handle booleans and etc. And additionally, I added dummy "ok": 1 key here, because at the moment, when you iterate the map, you can’t detect the last element in order to handle logic of adding ,. It probably can be solved later by defining special helper which implements counters.

Hope it helps!