amplify-cli icon indicating copy to clipboard operation
amplify-cli copied to clipboard

Custom resolver not retrieving list of records

Open johnEthicalTechnology opened this issue 6 years ago • 7 comments

Note: If your question is regarding the AWS Amplify Console service, please log it in the official AWS Amplify Console forum

Which Category is your question related to? AppSync custom resolvers.

Amplify CLI Version

You can use amplify -v to check the amplify cli version on your system 4.29.7

What AWS Services are you utilizing? AppSync, DynamoDB, Cognitio, IAM, Lambda

Provide additional details e.g. code snippets

I followed this tutorial to get a custom resolver to work.

This is the relevant parts of schema.graphql:

type MappingData
  @model
  @auth(
    rules: [
      { allow: private, operations: [update, read] }
      { allow: private, provider: iam, operations: [create, read] }
    ]
  ) {
  id: ID!
  formName: String
  formId: String
  pageId: String
  mappingInfo: MappingInfo
  rawLeadFields: [RawLeadField]
  status: Status
  formCreatedTime: String
  deliveryStatus: String
  errors: String
  campaignName: String
  campaignId: String
  archived: Boolean
  leads: [Lead] @connection(keyName: "byMappingData", fields: ["id"])
}

type Lead
  @model
  @key(name: "byMappingData", fields: ["mappingDataID"])
  @auth(
    rules: [
      { allow: private, operations: [update, read] }
      { allow: private, provider: iam, operations: [create, read] }
    ]
  ) {
  id: ID!
  formId: String!
  pageId: String!
  processedLeadData: String
  status: Status!
  deliveryStatus: DeliveryStatus!
  zohoResponse: String
  createdTime: String
  fbLeadId: String
  rawLeadData: [FieldData]
  mappingDataID: ID!
  mappingData: MappingData @connection(fields: ["mappingDataID"])
}

// This is the addition to the schema based on the above tutorial
type LeadConnection {
  leads: [Lead]
  nextToken: String
}

type Query {
  leadsForMappingInfo(
    mappingInfoId: ID!
    limit: Int
    nextToken: String
  ): LeadConnection
}

These are the vtl files I created

## Query.leadsForMappingInfo.req.vtl **

#set( $limit = $util.defaultIfNull($context.args.limit, 10) )
{
  "version": "2017-02-28",
  "operation": "Query",
  "query": {
    "expression": "#connectionAttribute = :connectionAttribute",
    "expressionNames": {
        "#connectionAttribute": "mappingDataID"
    },
    "expressionValues": {
        ":connectionAttribute": {
            "S": "$context.args.mappingInfoId"
        }
    }
  },
  "scanIndexForward": true,
  "limit": $limit,
  "nextToken": #if( $context.args.nextToken ) "$context.args.nextToken" #else null #end,
  "index": "byMappingData"
}

## Query.leadsForMappingInfo.res.vtl **

#if( $ctx.error )
$util.error($ctx.error.message, $ctx.error.type)
#else
$util.toJson($ctx.result)
#end

This is the relevant section of the CustomResources.json while everything else is kept as the same:

"Resources": {
    "EmptyResource": {
      "Type": "Custom::EmptyResource",
      "Condition": "AlwaysFalse"
    },
    "QueryLeadsForMappingInfoResolver": {
      "Type": "AWS::AppSync::Resolver",
      "Properties": {
        "ApiId": {
          "Ref": "AppSyncApiId"
        },
        "DataSourceName": "LeadTable",
        "TypeName": "Query",
        "FieldName": "leadsForMappingInfo",
        "RequestMappingTemplateS3Location": {
          "Fn::Sub": [
            "s3://${S3DeploymentBucket}/${S3DeploymentRootKey}/resolvers/Query.leadsForMappingInfo.req.vtl",
            {
              "S3DeploymentBucket": {
                "Ref": "S3DeploymentBucket"
              },
              "S3DeploymentRootKey": {
                "Ref": "S3DeploymentRootKey"
              }
            }
          ]
        },
        "ResponseMappingTemplateS3Location": {
          "Fn::Sub": [
            "s3://${S3DeploymentBucket}/${S3DeploymentRootKey}/resolvers/Query.leadsForMappingInfo.res.vtl",
            {
              "S3DeploymentBucket": {
                "Ref": "S3DeploymentBucket"
              },
              "S3DeploymentRootKey": {
                "Ref": "S3DeploymentRootKey"
              }
            }
          ]
        }
      }
    }
  },

When I'd finished and made a call to the query in the AppSync console I got the following error: Query condition missed key schema element: mappingDataID.

I then changed "#connectionAttribute": “leadMappingInfoId” to "#connectionAttribute": “mappingDataID”. (what it is currently) and that worked. However, it returned null results, which is unexpected.

This is the query for the custom resolver:

leadsForMappingInfo(mappingInfoId: "baef9144-02af-46eb-be54-5aac03a3807a") {
    leads {
      id
    }
  }

When I run:

listLeads(filter: {mappingDataID: {eq: "baef9144-02af-46eb-be54-5aac03a3807a"}}) {
    items {
      id
    }
  }

It returns 2 results, as expected.

Is there anything I'm doing wrong here? It's not exactly a blocker b/c I can use the listLeads query for what I want but I'll be needing to create a custom resolver pretty soon to batch update (following this tutorial and would like to know why this resolver isn't working as expected in case I come across a similar issue with the batch updating.

Thanks in advanced.

johnEthicalTechnology avatar Oct 14 '20 03:10 johnEthicalTechnology

hey @johnEthicalTechnology, your response mapping template needs to return an JSON object that matches the response type shape. The default response template works because the connection type has items as the field which is the same field used in DynamoDB.

If you update the response mapping template as below, you should see the result

## Query.leadsForMappingInfo.res.vtl **
#if( $ctx.error )
  $util.error($ctx.error.message, $ctx.error.type)
#else
  $util.toJson({"leads": $ctx.result.items, "nextToken": $ctx.result.nextToken})
#end

yuth avatar Oct 14 '20 19:10 yuth

Thanks for the quick reply! That fixed it!

I've just got another quick question. I've successfully been able to create a batchUpdate resolver, however, my first iteration only passed in the value for two fields. This cause only those two fields to be updated and all the other fields to be updated to blank.

For the second iteration I passed in the all the fields. This was successful in updating the required fields with new data and keeping the fields with the current data.

Is it possible to pass in only two fields with updated data but then don't update anything else and keep the value in all the other fields as is? Or is the only way to do that is to pass in the entire object?

johnEthicalTechnology avatar Oct 16 '20 04:10 johnEthicalTechnology

Are you using BatchWrite to do batchUpdate? DynamoDB does not allow updating items with batchWrite and they recommend using UpdateItem instead when you have to change an existing item

yuth avatar Oct 16 '20 21:10 yuth

I'm using BatchPutItem. This is the code for the resolver request.

#if( $authCondition && $authCondition.expression != "" )
  #set( $condition = $authCondition )
  #if( $modelObjectKey )
    #foreach( $entry in $modelObjectKey.entrySet() )
      $util.qr($condition.put("expression", "$condition.expression AND attribute_exists(#keyCondition$velocityCount)"))
      $util.qr($condition.expressionNames.put("#keyCondition$velocityCount", "$entry.key"))
    #end
  #else
    $util.qr($condition.put("expression", "$condition.expression AND attribute_exists(#id)"))
    $util.qr($condition.expressionNames.put("#id", "id"))
  #end
#else
  #if( $modelObjectKey )
    #set( $condition = {
  "expression": "",
  "expressionNames": {},
  "expressionValues": {}
} )
    #foreach( $entry in $modelObjectKey.entrySet() )
      #if( $velocityCount == 1 )
        $util.qr($condition.put("expression", "attribute_exists(#keyCondition$velocityCount)"))
      #else
        $util.qr($condition.put("expression", "$condition.expression AND attribute_exists(#keyCondition$velocityCount)"))
      #end
      $util.qr($condition.expressionNames.put("#keyCondition$velocityCount", "$entry.key"))
    #end
  #else
    #set( $condition = {
  "expression": "attribute_exists(#id)",
  "expressionNames": {
      "#id": "id"
  },
  "expressionValues": {}
} )
  #end
#end
#set($leadsdata = [])
#foreach($lead in ${ctx.args.leads})
    ## Automatically set the updatedAt timestamp. **
    $util.qr($lead.put("updatedAt", $util.defaultIfNull($ctx.args.input.updatedAt, $util.time.nowISO8601())))
    $util.qr($lead.put("__typename", "Lead"))
    $util.qr($lead.put("status", "ACTIVE"))
    $util.qr($leadsdata.add($util.dynamodb.toMapValues($lead)))
#end
{
    "version" : "2018-05-29",
    "operation" : "BatchPutItem",
    "tables" : {
        "Lead-kkbs55pjjrbltj2bi3zewybnfu-prod": $utils.toJson($leadsdata)
    }
}

johnEthicalTechnology avatar Oct 17 '20 02:10 johnEthicalTechnology

If you look at the permission documented here internally AppSync uses dynamodb:BatchWriteItem. With BatchWriteItem, you can overwrite an item, but you will have set all the fields. So your resolvers will have to set all the fields even when its an update

yuth avatar Oct 20 '20 16:10 yuth

Great, thanks for that!

johnEthicalTechnology avatar Oct 20 '20 22:10 johnEthicalTechnology

This issue has been automatically locked since there hasn't been any recent activity after it was closed. Please open a new issue for related bugs.

Looking for a help forum? We recommend joining the Amplify Community Discord server *-help channels for those types of questions.

github-actions[bot] avatar May 25 '21 18:05 github-actions[bot]