Describe the bug
Hello,
I am using Aurora Serverless as a data source.
When amplify generates code for the response templates, there are basically 2 types, one for elements, and the other one for collections:
$utils.toJson($utils.rds.toJsonObject($ctx.result)[0][0])
and
$utils.toJson($utils.rds.toJsonObject($ctx.result)[0])
The problem I have is that, when I use a query that returns one elements, instead of a collection, like for example getPost/getComment/getUser or similar, if the element that I am requesting is not in the data base (or the id I am passing is wrong), then I receive this error:
message": "Error invoking method 'get(java.lang.Integer)' in java.util.ArrayList at velocity[line 4, column 54]"
I guess the reason is because there is no data structure at [0][0].
So, should I modify my template doing something like?:
#if ($context.source.WHATEVER == 0)
#return([])
#end
$utils.toJson($utils.rds.toJsonObject($ctx.result)[0][0])
What do you think about this? Thanks.
Amplify CLI Version
4.2.0
To Reproduce
Use Amazon Serverless as a data source for AppSync. Generate code using "amplify api" and "amplify api add-graphql-datasource"
Expected behavior
I should receive no element, not sure as an error or as an empty element. But not that strange error message about javascript.
Desktop (please complete the following information):
Additional context
Can you explain to me how I should solve this problem manually (while you fix the code generation)?
EDIT: I guess the same would happen with collections when the collection is empty. I didn't try that tough.
EDIT2: Here more info about how to solve it: https://adrianhall.github.io/cloud/2019/01/03/early-return-from-graphql-resolvers/
I fixed this crash with this code:
#set($output = $utils.rds.toJsonObject($ctx.result)[0])
#if ($output.isEmpty())
null
#else
$utils.toJson($output[0])
#end
I tested it for single element queries (instead of collections) and works perfectly in both cases (no element, element)
I would recommend to add something like this to the code generator.
Most helpful comment
I fixed this crash with this code:
I tested it for single element queries (instead of collections) and works perfectly in both cases (no element, element)
I would recommend to add something like this to the code generator.