7

What would be the right way to change json response key value in aws appsync response mapping template?

JSON that I get looks like this:

{
  "tenant_id": 1,
  "id": "bd8ce6a8-8532-47ec-8b7f-dcd1f1603320",
  "header": "Header name",
  "visible": true
}

and what I would like to pass forward is

{
  "tenantId": 1,
  "id": "bd8ce6a8-8532-47ec-8b7f-dcd1f1603320",
  "header": "Header name",
  "visible": true
}

Schema wants tenant id in form of tenantID and lambda returns it in form of tenant_id. I could change it in lambda but I would like to know how to do it in response mapping template.

Shankar Raju
  • 4,356
  • 6
  • 33
  • 52
Toni Kuutti
  • 93
  • 2
  • 5

1 Answers1

7

You could do this via the response mapping template for the field you are resolving to in the following manner:

Consider the JSON response from your lambda to be stored in the response variable, then you can return something like this.

$#set($result = {
 "tenantId": ${response.tenant_id},
 "id": "${response.id}",
 "header": "${response.header}",
 "visible": $response.visible
})

$util.toJson($result)

Alternatively, you could also mutate your response from the lambda by setting a tenantId field, something like #set( $response.tenantId = $response.tenant_id ). Let me know if you still face an issue.

Thanks, Shankar

Shankar Raju
  • 4,356
  • 6
  • 33
  • 52
  • I ended up using Lodash mapKeys and cameCase methods in the lambda handler so I could do it in one place for all GraphQL queries. But it is useful to know the response mapping way too for special cases. Thank you! – Toni Kuutti Aug 02 '18 at 14:33
  • 1
    I wanted to do something similar with a response coming from DynamoDB instead of lambda. For an unknown reason, your second solution `#set( $ctx.result.newkey = $ctx.result.oldkey)` (which I prefer as it keeps the rest of the data intact) doesn't work (my new key is always null). So I implemented the first one and it works like a charm. Thanks :) – Edwin Joassart Aug 14 '18 at 13:57