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

How to call a lambda function from an overwritten resolvers?

Open mjza opened this issue 5 years ago • 13 comments

Assume I have the following simple model:

type User
@model 
{
    id: ID!
    firstname: String
    lastname: String
    email: AWSEmail
}

This model would generate some mutations and I want to overwrite the createUser. Therefore, I have copied the original code from appsync and added a snippet of custom code on top of it.

## <project-root>/amplify/backend/api/<api-name>/resolvers/Mutation.CreateUser.req.vtl
## [Start] Customized code
#set($valid = $util.matches("^[a-zA-Z0-9_.+-]+@(?:(?:[a-zA-Z0-9-]+\.)?[a-zA-Z]+\.)?(cimt)\.de", $ctx.args.input.email))
#if (!$valid)
    $util.error("$ctx.args.input.email is not a valid email.")
#end
## [End] Customized code
## [Start] Set default values. **
$util.qr($context.args.input.put("id", $util.defaultIfNull($ctx.args.input.id, $util.autoId())))
#set( $createdAt = $util.time.nowISO8601() )
## Automatically set the createdAt timestamp. **
$util.qr($context.args.input.put("createdAt", $util.defaultIfNull($ctx.args.input.createdAt, $createdAt)))
## Automatically set the updatedAt timestamp. **
$util.qr($context.args.input.put("updatedAt", $util.defaultIfNull($ctx.args.input.updatedAt, $createdAt)))
## [End] Set default values. **
## [Start] Prepare DynamoDB PutItem Request. **
$util.qr($context.args.input.put("__typename", "User"))
#if( $modelObjectKey )
  #set( $condition = {
  "expression": "",
  "expressionNames": {},
  "expressionValues": {}
} )
  #foreach( $entry in $modelObjectKey.entrySet() )
    #if( $velocityCount == 1 )
      $util.qr($condition.put("expression", "attribute_not_exists(#keyCondition$velocityCount)"))
    #else
      $util.qr($condition.put("expression", "$condition.expression AND attribute_not_exists(#keyCondition$velocityCount)"))
    #end
    $util.qr($condition.expressionNames.put("#keyCondition$velocityCount", "$entry.key"))
  #end
#else
  #set( $condition = {
  "expression": "attribute_not_exists(#id)",
  "expressionNames": {
      "#id": "id"
  },
  "expressionValues": {}
} )
#end
#if( $context.args.condition )
  #set( $condition.expressionValues = {} )
  #set( $conditionFilterExpressions = $util.parseJson($util.transform.toDynamoDBConditionExpression($context.args.condition)) )
  $util.qr($condition.put("expression", "($condition.expression) AND $conditionFilterExpressions.expression"))
  $util.qr($condition.expressionNames.putAll($conditionFilterExpressions.expressionNames))
  $util.qr($condition.expressionValues.putAll($conditionFilterExpressions.expressionValues))
#end
#if( $condition.expressionValues && $condition.expressionValues.size() == 0 )
  #set( $condition = {
  "expression": $condition.expression,
  "expressionNames": $condition.expressionNames
} )
#end
{
  "version": "2018-05-29",
  "operation": "PutItem",
  "key": #if( $modelObjectKey ) $util.toJson($modelObjectKey) #else {
  "id":   $util.dynamodb.toDynamoDBJson($ctx.args.input.id)
} #end,
  "attributeValues": $util.dynamodb.toMapValuesJson($context.args.input),
  "condition": $util.toJson($condition)
}
## [End] Prepare DynamoDB PutItem Request. **

I have a small question. I want to move the following customized part of the code to a lambda function and to be able to call it in several places.

## [Start] Customized code
#set($valid = $util.matches("^[a-zA-Z0-9_.+-]+@(?:(?:[a-zA-Z0-9-]+\.)?[a-zA-Z]+\.)?(cimt)\.de", $ctx.args.input.email))
#if (!$valid)
    $util.error("$ctx.args.input.email is not a valid email.")
#end
## [End] Customized code

I tried to modify this example: https://docs.amplify.aws/cli/graphql-transformer/resolvers#add-a-custom-resolver-that-targets-an-aws-lambda-function

And put the following code on top of the Mutation.createUser.req.vtl file:

{
  "version": "2017-02-28",
  "operation": "Invoke",
  "payload": {
    "type": "Mutation",
    "field": "createUser",
    "arguments": $utils.toJson($context.arguments),
    "identity": $utils.toJson($context.identity),
    "source": $utils.toJson($context.source)
  }
}

However, it seems it is not that straight forward that I thought. Any help is appreciated.

mjza avatar Jul 23 '21 13:07 mjza

The source of problem or my mistake is somewhere in the CustomResources.json. How can I provide suitable code in Resources block to be able to call a lambda function in my resolver. After modifications I reached this that causes the problem:

"Resources": {
    "EmptyResource": {
      "Type": "Custom::EmptyResource",
      "Condition": "AlwaysFalse"
    },
    "EchoLambdaDataSource": {
      "Type": "AWS::AppSync::DataSource",
      "Properties": {
        "ApiId": {
          "Ref": "AppSyncApiId"
        },
        "Name": "EchoFunction",
        "Type": "AWS_LAMBDA",
        "ServiceRoleArn": {
          "Fn::GetAtt": [
            "EchoLambdaDataSourceRole",
            "Arn"
          ]
        },
        "LambdaConfig": {
          "LambdaFunctionArn": {
            "Fn::Sub": [
              "arn:aws:lambda:${AWS::Region}:${AWS::AccountId}:function:echofunction-${env}",
              { "env": { "Ref": "env" } }
            ]
          }
        }
      }
    },
    "EchoLambdaDataSourceRole": {
      "Type": "AWS::IAM::Role",
      "Properties": {
        "RoleName": {
          "Fn::Sub": [
            "EchoLambdaDataSourceRole-${env}",
            { "env": { "Ref": "env" } }
          ]
        },
        "AssumeRolePolicyDocument": {
          "Version": "2012-10-17",
          "Statement": [
            {
              "Effect": "Allow",
              "Principal": {
                "Service": "appsync.amazonaws.com"
              },
              "Action": "sts:AssumeRole"
            }
          ]
        },
        "Policies": [
          {
            "PolicyName": "InvokeLambdaFunction",
            "PolicyDocument": {
              "Version": "2012-10-17",
              "Statement": [
                {
                  "Effect": "Allow",
                  "Action": [
                    "lambda:invokeFunction"
                  ],
                  "Resource": [
                    {
                      "Fn::Sub": [
                        "arn:aws:lambda:${AWS::Region}:${AWS::AccountId}:function:echofunction-${env}",
                        { "env": { "Ref": "env" } }
                      ]
                    }
                  ]
                }
              ]
            }
          }
        ]
      }
    },
    "MutationCreateUserResolver": {
      "Type": "AWS::AppSync::Resolver",
      "Properties": {
        "ApiId": {
          "Ref": "AppSyncApiId"
        },
        "DataSourceName": {
          "Fn::GetAtt": [
            "EchoLambdaDataSource",
            "Name"
          ]
        },
        "TypeName": "Mutation",
        "FieldName": "createUser",
        "RequestMappingTemplateS3Location": {
          "Fn::Sub": [
            "s3://${S3DeploymentBucket}/${S3DeploymentRootKey}/resolvers/Mutation.createUser.req.vtl",
            {
              "S3DeploymentBucket": {
                "Ref": "S3DeploymentBucket"
              },
              "S3DeploymentRootKey": {
                "Ref": "S3DeploymentRootKey"
              }
            }
          ]
        },
        "ResponseMappingTemplateS3Location": {
          "Fn::Sub": [
            "s3://${S3DeploymentBucket}/${S3DeploymentRootKey}/resolvers/Mutation.createUser.res.vtl",
            {
              "S3DeploymentBucket": {
                "Ref": "S3DeploymentBucket"
              },
              "S3DeploymentRootKey": {
                "Ref": "S3DeploymentRootKey"
              }
            }
          ]
        }
      }
    }
  },

Error says: Only one resolver is allowed per field.

mjza avatar Jul 23 '21 13:07 mjza

Can anybody provide an answer for this question?

nielsautrata avatar Jul 27 '21 05:07 nielsautrata

generally speaking there is no way to “call” a lambda function. you can convert that resolver to be a pipeline resolver where 1 stage in the pipeline (or more) can be a lambda invocation. I’m sure there are samples for appsync out there on this, not sure about CLI samples.

johnpc avatar Jul 30 '21 17:07 johnpc

Hey @mjza :wave: were you able to leverage a pipeline resolver to invoke a Lambda?

josefaidt avatar Aug 11 '21 15:08 josefaidt

Does pipeline resolver work with DataStore, though? Correct me if I'm wrong, but I don't think it does. For those of us who have to rely on the DataStore and complex resolver logic, this is a deal breaker.

ldwii avatar Aug 13 '21 20:08 ldwii

Amplify already supports triggering Lambdas post DynamoDB record update for @model-generated types. Why not at least allows developers to choose between VTL and Lambda?

ldwii avatar Aug 13 '21 20:08 ldwii

Hey @mjza 👋 were you able to leverage a pipeline resolver to invoke a Lambda?

@josefaidt The problem of pipeline resolver is, it does not support with cli and if I change the schema and push the back-end, then I must go to AWS appsync and redo all my configurations for pipeline resolvers!

mjza avatar Aug 16 '21 06:08 mjza

Hey @mjza can you share a few details about how you're adding the pipeline resolver? Is this done through the console? You should be able to add a custom resolver and add it as a pipeline resolver to the CustomResources.json file. Please refer to this documentation page for more information about adding resolvers to the CustomResources file, and I came across this blog post on Dev.to that walks through setting up pipeline resolvers.

josefaidt avatar Aug 18 '21 18:08 josefaidt

Hey @mjza just wanted to follow-up to my previous message and see if you were able to leverage the CustomResources.json file to add pipeline resolvers

josefaidt avatar Sep 02 '21 21:09 josefaidt

Hi @josefaidt, Sorry I've been occupied with other projects, I will come back to this project soon.

mjza avatar Sep 04 '21 06:09 mjza

Hey @mjza no worries! Thanks for getting back with me!

josefaidt avatar Sep 07 '21 14:09 josefaidt

Closing due to inactivity. @mjza if you run into this issue again please reply back to this thread and we can re-open to investigate further 🙂

josefaidt avatar Sep 23 '21 15:09 josefaidt

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 Nov 23 '21 01:11 github-actions[bot]