Search code examples
amazon-web-servicesaws-appsyncvtl

How to fix this error in my appsync while creating an array of data


I am creating an array of date and in my resolver it only return one output of date and count audited

I search throughout the google to find some answer and I found a code how to make an array of list but the problem is it didn't return well

https://i.sstatic.net/bcRHc.jpg this is a result and the code I use it attached in the picture

#set ($tu = 0) #set ($pc = 0) #set ($fc = 0) #set ($da = [])#set ($cda = [])                                                                  #foreach($item in $ctx.result.items)
#set($tu = $item.total_audits + $tu)
#set($pc = $item.passed_compliance + $pc)
#set($fc = $item.failed_compliance + $fc)
#set($date = $item.sort)
#set($count = $item.total_audits)
$util.qr($da.add("$date"))
$util.qr($cda.add("$count"))
#end
$util.toJson({"total_audits":$tu, "passed_compliance":$pc,
"failed_compliance":$fc, "daily_audit": [{"date": $da, "count": $cda}]})

here is the error

 "errors": [
{
  "path": [
    "getAuditSummary",
    "daily_audit",
    0,
    "date"
  ],
  "locations": null,
  "message": "Can't serialize value (/getAuditSummary/daily_audit[0]/date) : Unable to serialize `[2018-12-26, 2018-12-27, 2018-12-28]` as a valid date."
},
{
  "path": [
    "getAuditSummary",
    "daily_audit",
    0,
    "count"
  ],
  "locations": null,
  "message": "Can't serialize value (/getAuditSummary/daily_audit[0]/count) : Expected type 'Int' but was 'ArrayList'."

what i want to make is it would return something like this

 "daily_audit": [
        {
          "date": 2018-12-26,
          "count": 1
        }
        {
          "date": 2018-12-27,
          "count": 4
        }
        {
          "date": 2018-12-28,
          "count": 2
        }
]

Solution

  • This is happening because $da and $cda are arrays. So it's probably returning:

    "daily_audit": [
        {
          "date": [2018-12-26,2018-12-27,2018-12-28],
          "count": [1,4,2]
        }
    ]
    

    So, in your response mapping template, you can try something like:

    #set ($tu = 0) 
    #set ($pc = 0) 
    #set ($fc = 0) 
    #set ($da = [])                                                          
    
    #foreach($item in $ctx.result.items)
        #set($tu = $item.total_audits + $tu)
        #set($pc = $item.passed_compliance + $pc)
        #set($fc = $item.failed_compliance + $fc)
        #set($date = $item.sort)
        #set($count = $item.total_audits)
        $util.qr($da.add({"date":$date, "count":$count}))
    #end
    $util.toJson({"total_audits":$tu, "passed_compliance":$pc, "failed_compliance":$fc, "daily_audit": $da})