3

I'm writing code for my GraphQL resolvers in AWS AppSync with resolver mapping template.

I know that there is a put mehtod that I can use for add a field to input object or any other object. Like this (for example):

$util.qr($name.put("firstName", "$ctx.args.input.firstName"))

But now I want to remove a field from an object, for example, the input object. Is there any mehtod similar to the put method but for removing a field. something like:

$util.qr($ctx.args.input.remove("firstName"))

I am new to AWS and DynamoDB and AppSync.( you can consider me as an absolute beginner. )

Rajan Sharma
  • 2,211
  • 3
  • 21
  • 33
Orilious
  • 331
  • 5
  • 16

3 Answers3

2

Use foreach and make a new array.

#set($newInput={})

#foreach ($key in $ctx.args.input.keySet())
  #if($key!="firstName")
     $util.qr($newInput.put($key, $ctx.args.input.get($key)))
  #end
#end
uchar
  • 2,552
  • 4
  • 29
  • 50
  • So actually you didn't remove it. you move other fields to a new one. like examples I saw... could be good. so isn't a way to really remove that field from the `input` itself? – Orilious Oct 10 '19 at 12:54
2

Yes, generally you can use $myObject.remove("myKey") on objects that you create in a mapping template, however, I will add the disclaimer that this will not always work on objects in the $ctx as some parts are immutable. AppSync bundles utility methods that make dealing with objects in mapping templates easier (e.g. making copies of objects). This functionality is actually tied to that of Apache Velocity so you can read more about how it works in those docs.

mparis
  • 3,623
  • 1
  • 17
  • 16
  • Utility methods are convenient but VTL functionality is restricted because macros are blocked. That might change though (please please please...!): https://github.com/aws/aws-appsync-community/issues/90 – Ben May 19 '20 at 11:35
1

In AppSync, the arguments in a query or mutation are exposed in the request mapping template as $context.args. If you have passed in an argument named input you can remove it as follows:

$util.quiet($context.args.remove("input"))

or its using the alias for quiet (identical to the above):

$util.qr($context.args.remove("input"))

This can be used in both the request and response mapping template. It can also be used to remove nested properties:

$util.qr($context.args.input.remove("nestedProp"))

Toomy
  • 318
  • 2
  • 10