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

How Do I get amplify environment variables into custom resolvers mapping template.

Open damianrr opened this issue 7 years ago • 12 comments

Is your feature request related to a problem? Please describe. I'm always frustrated when I need to hardcode tablenames in mapping templates, this happens often with batch operations that require the tablename, for example:

#set($ids = [])
#foreach($id in ${ctx.args.ids})                                                                  
  #set($map = {})
  $util.qr($map.put("id", $util.dynamodb.toString($id)))              
  $util.qr($ids.add($map))
#end

{                                                                                                                 
  "version" : "2018-05-29",
  "operation" : "BatchGetItem",
  "tables" : {
    "MyTablename-GraphQLIDRandomThing-Env": {
      "keys": $util.toJson($ids),
      "consistentRead": true
    }
  }
}

Describe the solution you'd like

If I could have access to env name and GraphqlID I'd be able to construct the table name instead of hardcoding it.

Thanks!!

damianrr avatar Jun 20 '19 19:06 damianrr

A less desirable alternative would be a $util function that returns the tablename of the associated datasource. It is less desirable because it only solves the problem for single table batch operations -- but it may be easier to implement. On the other hand, this solution would be independent of Amplify (i.e., it would solve the problem for Appsync users not using Amplify as long as they are doing single-table applications).

ericweissmann avatar Sep 28 '19 11:09 ericweissmann

OK, here's the solution for getting an environment variable into an Appsync resolver (facepalm) in an Amplify project.

Create a function in a custom cloudformation stack that sticks the desired environment variable(s) in $ctx.stash. Then you can refer to it whenever you want. Here's my function resource declaration:

"getEnvironmentFunction": {
  "Type": "AWS::AppSync::FunctionConfiguration",
  "Properties": {
    "ApiId": {
      "Ref": "AppSyncApiId"
    },
    "DataSourceName": {
      "Fn::GetAtt": [
        "NoneDS",
        "Name"
      ]
    },
    "Description": "Sets $ctx.stash.environment equal to the Amplify development environment pushed",
    "FunctionVersion": "2018-05-29",
    "Name": "getEnvironment",
    "RequestMappingTemplate": "{\n          \"version\": \"2017-02-28\",\n          \"payload\": {}\n        }",
    "ResponseMappingTemplate": {
      "Fn::Join": [
        "",
        [
          "$util.qr($context.stash.put(\"environment\", \"",
          { "Ref" : "env" },
          "\"))\n$util.toJson($ctx.prev.result)"
        ]
      ]
    }
  }
}

Note that you need a "none" datasource (here it is called 'NoneDS').

ericweissmann avatar Sep 30 '19 08:09 ericweissmann

@ericweissmann does your solution work for custom resolvers? Meaning it will run before every resolver?

kldeb avatar Apr 11 '20 14:04 kldeb

@ericweissmann does your solution work for custom resolvers? Meaning it will run before every resolver?

As I understand it, you will have to create a Pipeline resolver that calls the above function, then your resolver. So you will need to define this function in custom resources (and include the AppSyncApiId variable if you're doing a batch operation), then your custom resolver function, then a pipeline resolver that calls them both.

Add the variables to the stash

"addEnvVariablesToStash": {
  "Type": "AWS::AppSync::FunctionConfiguration",
  "Properties": {
    "ApiId": {
      "Ref": "AppSyncApiId"
    },
    "DataSourceName": "NONE",
    "Description": "Sets $ctx.stash.env to the Amplify environment and $ctx.stash.apiId to the Amplify API ID",
    "FunctionVersion": "2018-05-29",
    "Name": "addEnvVariablesToStash",
    "RequestMappingTemplate": "{\n          \"version\": \"2017-02-28\",\n          \"payload\": {}\n        }",
    "ResponseMappingTemplate": {
      "Fn::Join": [
        "",
        [
          "$util.qr($context.stash.put(\"env\", \"",
          { "Ref" : "env" },
          "\"))\n$util.qr($context.stash.put(\"apiId\", \"",
	  { "Ref": "AppSyncApiId" },
	  "\"))\n$util.toJson($ctx.prev.result)"
        ]
      ]
    }
  }
},

Your custom resolver function

"FunctionMutationDoThing": {
  "Type": "AWS::AppSync::FunctionConfiguration",
  "Properties": {
    "ApiId": {
      "Ref": "AppSyncApiId"
    },
    "DataSourceName": "MyTableName",
    "FunctionVersion": "2018-05-29",
    "Name": "FunctionMutationDoThing",
    "RequestMappingTemplateS3Location": {
      "Fn::Sub": [
        "s3://${S3DeploymentBucket}/${S3DeploymentRootKey}/resolvers/Function.Mutation.doThing.req.vtl",
        {
         "S3DeploymentBucket": {
           "Ref": "S3DeploymentBucket"
         },
         "S3DeploymentRootKey": {
             "Ref": "S3DeploymentRootKey"
           }
         }
       ]
     },
    "ResponseMappingTemplateS3Location": {
      "Fn::Sub": [
        "s3://${S3DeploymentBucket}/${S3DeploymentRootKey}/resolvers/Function.Mutation.doThing.res.vtl",
        {
         "S3DeploymentBucket": {
           "Ref": "S3DeploymentBucket"
         },
         "S3DeploymentRootKey": {
             "Ref": "S3DeploymentRootKey"
           }
         }
       ]
     }
  }
},

Your pipeline resolver that calls the first and second functions above

"PipelineMutationDoThingResolver": {
  "Type": "AWS::AppSync::Resolver",
  "Properties": {
    "ApiId": {
      "Ref": "AppSyncApiId"
    },
    "Kind": "PIPELINE",
    "PipelineConfig": {
      "Functions": [
        {
          "Fn::GetAtt": ["addEnvVariablesToStash", "FunctionId"]
        },
        {
          "Fn::GetAtt": ["FunctionMutationDoThing", "FunctionId"]
        }
      ],
      "TypeName": "Mutation",
      "FieldName": "doThing",
      "RequestMappingTemplate": "{}",
      "ResponseMappingTemplate": "$util.toJson($ctx.result)"
     },
   "DependsOn": ["addEnvVariablesToStash", "FunctionMutationDoThing"]
  }
}

Then you can reference the variables in your Function.Mutation.doThing.req.vtl function with: $ctx.stash.env $ctx.stash.apiId

Hope that makes sense. Just thought it was worth putting up the full solution. Seeing as @ericweissmann 's solution has been heavily referenced (and stopped me from tearing my hair out!).

jonperryxlm avatar Jun 03 '20 02:06 jonperryxlm

@jonperryxlm thanks for the explanation. Was really helpful. I'm kinda new to amplify and the customer resolver file is looking foreign to me. is this the right way to access the resolver $ctx.stash in the resolver file?

{                                                                                                                 
  "version" : "2018-05-29",
  "operation" : "BatchGetItem",
  "tables" : {
    "MyTablename-$ctx.stash.env-$ctx.stash.apiId": {
      "keys": $util.toJson($ids),
      "consistentRead": true
    }
  }
}

Somtozech avatar Aug 04 '20 20:08 Somtozech

@jonperryxlm thanks for the explanation. Was really helpful. I'm kinda new to amplify and the customer resolver file is looking foreign to me. is this the right way to access the resolver $ctx.stash in the resolver file? ...

@Somtozech I've updated your example to use the correct syntax...

{                                                                                                                 
  "version" : "2018-05-29",
  "operation" : "BatchGetItem",
  "tables" : {
    "MyTablename-${ctx.stash.env}-${ctx.stash.apiId}": {
      "keys": $util.toJson($ids),
      "consistentRead": true
    }
  }
}

Though I'm guessing it should actually be:

"MyTablename-${ctx.stash.apiId}-${ctx.stash.env}" as that's the naming convention for @model generated DynamoDB table names.

The resolvers are Velocity Templates, which if you're mainly focused on something like JavaScript (as I am), it does look weird. You can find the docs here - They aren't great. The AWS Resolver Mapping Template docs are decent.

I went through a fair amount of pain with the learning curve, mainly just down the code being so damn unreadable. My advice would be to play around with the code in the AppSync UI to test out your changes before putting it into source control, building it etc. (assuming you've got a sandbox type environment or similar). I know the AppSync UI is painfully slow, but it's way quicker than building and pushing just to realise you've made a stupid syntax error. Seems a no-duh type suggestion, but I didn't think to do it for ages!

Good luck, and hope that helps!

jonperryxlm avatar Aug 04 '20 21:08 jonperryxlm

@jonperryxlm did you experience this or know how I might solve it? image

Somtozech avatar Aug 04 '20 23:08 Somtozech

Oh. I was able to resolve this by creating a data source named NONE pointing to None as the source type from the appsync console

Somtozech avatar Aug 05 '20 09:08 Somtozech

Oh. I was able to resolve this by creating a data source named NONE pointing to None as the source type from the appsync console

@Somtozech you can create that none data source in the CustomResources.json file. You will probably overwrite that none data source when you push your next set of changes.

here's an example of my none data source under the Resources object:

    "NoneDataSource": {
      "Type": "AWS::AppSync::DataSource",
      "Properties": {
        "ApiId": {
          "Ref": "AppSyncApiId"
        },
        "Name": "NoneDataSource",
        "Type": "NONE"
      }
    },

kldeb avatar Aug 05 '20 13:08 kldeb

Closing this in favor of aws-amplify/amplify-category-api#408 to increase visibility.

SwaySway avatar Aug 12 '20 19:08 SwaySway

How you call this? the Pipeline resolver within the schema??? Some how I am having issue,

Invalid template property or properties

idobleicher avatar Jan 06 '21 19:01 idobleicher

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 09:05 github-actions[bot]