The Lambda data source calls the configured Lambda function and returns its result. This is the most versatile data source, as a Lambda function can do any processing, such as getting items from databases, call other functions, and even interact with third-party resources. Because of this, it's a best practice to implement complex functionality with a Lambda data source.
To add the data source, you'll need two things: the Lambda function that AppSync will call and a role that gives permission to do that. As usual, the role needs to allow the AppSync service in its trust policy:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Service": "appsync.amazonaws.com"
},
"Action": "sts:AssumeRole"
}
]
}
Then it needs to allow the lambda:InvokeFunction
in its permissions policy:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "",
"Effect": "Allow",
"Action": [
"lambda:InvokeFunction",
],
"Resource": [
"arn:aws:lambda:...:function:..."
]
},
]
}
Notice that there are two layers of permissions working here. First, AppSync uses a role to call the Lambda function. But then the Lambda function uses another role to access resources in the account, such as databases or other functions.
Use environment variables for the Lambda function to pass configuration to the function, such as the name of DynamoDB tables, S3 bucket names, and other non-changing values.
In the request mapping template you can define what the Lambda function gets in the event
object. For example, this template passes the field arguments and a constant text to the function:
return {
version: "2018-05-29",
operation: "Invoke",
payload: {
arguments: ctx.args,
extra_data: "something else"
}
}
For a field, such as field(fieldArg: String)
, the event
object will be:
{
arguments:{
fieldArg: "arg1"
},
extra_data: "something else"
}