How to mutate AWS GraphQL using AWS Lambda
Recently, I had to create a AWS Lambda trigger for the AWS DynamoDB table events. The tricky part on this thing was to mutate AWS GraphQL using AWS Lambda with this DynamoDB event. The reason was I wanted all the clients which were subscribed to GraphQL to get this event with modified data.
The problem was how to authenticate Lambda and communicate with AppSync. My mobile application was using the AWS Cognito credentials for AWS service authentication. Therefore, with the current setup I used the AWS IAM policies to authenticate the lambda function to do mutations.
Change AppSync Auth Mode to mutate AWS GraphQL using AWS Lambda
First of all, go to the AppSync and change the auth mode to AWS Identity and Access Management (IAM)
Furthermore, use following steps to create the lambda function.
Create IAM policy to authenticate AppSync endpoint
Go to your IAM console and create the following Policy with an appropriate name.
{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "appsync:GraphQL" ], "Resource": [ "arn:aws:appsync:**-region-**:**Identity-Pool-ARN******:apis/******AppSync-API-ID***/*" ] } ] }
Region: Your AWS Region:
Identity Pool ARN:
click on edit identity pool and select Show ARN
AppSync Id:
After creating this policy, attach it to the AWS Lambda executing role. Note that you can always give /*
for your GraphQL endpoint which is the default Invocation Policy likewise.
After that, create the Lambda function which can invoke the GraphQL function. For that I used Axios library. You can use any other library option too.
const AWS = require('aws-sdk'); const axios = require('node_modules/axios/lib/axios.js'); exports.handler = async (event) => { AWS.config.update({ region: 'us-****-*', credentials: new AWS.Credentials({ accessKeyId: "*******", secretAccessKey: "***********", }) }); const result = await invokeAppSync({ user1: 'dummy1', user2: 'dummy2' }); console.log(result) return result.data; }; const invokeAppSync = async ({ user1, user2 }) => { let req = new AWS.HttpRequest('https://****.appsync-api.us-****-1.amazonaws.com/graphql', 'us-****-*'); req.method = 'POST'; req.headers.host = '******.appsync-api.us-****-*.amazonaws.com'; req.headers['Content-Type'] = 'multipart/form-data'; req.body = JSON.stringify({ "query":"mutation ($input: CreateMatchInput!) { createMatch(input: $input){ matchId } }", "variables": { "input": { "matchId": "dummyid", "matchUser1": user1, "matchUser2": user2, "timestamp": `${Date.now()}` } } }); let signer = new AWS.Signers.V4(req, 'appsync', true); signer.addAuthorization(AWS.config.credentials, AWS.util.date.getDate()); const result = await axios({ method: 'post', url: 'https://*******.appsync-api.us-****-*.amazonaws.com/graphql', data: req.body, headers: req.headers }); return result; });
For this lambda function, create an access key from IAM identity users. Most importantly, this access key is using for the API signing.
Finally, if you came to this point, the job is done. This will create a AppSync mutation for the lambda function and the apps will get the subscription data.
Troubleshooting
If you get the error
appsync:GraphQL write EPROTO 139686890170176:error:14077410:SSL routines:SSL23_GET_SERVER_HELLO:sslv3 alert handshake failure:../deps/openssl/openssl/ssl/s23_clnt.c:802
Remember to correctly add https and properly add host address in request. Remove the /graphql endpoint in the url.
If you need a way to connect the AppSync with a mobile app in a tricky situation use this tutorial: https://sandny.com/2018/06/28/create-aws-graphql-message-app/
Add a comment if you need any clarification in creating an AWS GraphQL from the AWS Lambda .
12 COMMENTS
Very nice example
I wish AWS would document stuff like this better.
I’m having some difficulty working out the correct req.body for my particular schema but I’ll figure it out eventually 😉
Just wanted to say thanks for posting this
Appreciate very much @disqus_QVEpRvVJRZ:disqus! Yes indeed, AWS should invest more money on documentations. At least, to make some books and distribute in kindle 😉
I’m gone to tell my little brother, that he should also pay a visit this blog on regular basis to get updated
from most recent reports.
Feel free to surf to my homepage: Sead-hair
Both the patient and the doctor often don t have a high level of suspicion it is breast cancer, said Sharon Giordano, Bogler s oncologist 60mg priligy
UK Carolyn Wickware, Pharmacists unqualified to follow government switching protocols, The Pharmaceutical Journal, 10 May 2019 cialis on line
types of allergy pills tablet for allergy on skin prescription vs over the counter
top rated heartburn relief avapro 300mg cheap
I truly appreciate your technique of writing a blog. I added it to my bookmark site list and will
rybelsus 14 mg tablet rybelsus 14 mg cost rybelsus 14 mg tablet
cyclobenzaprine 15mg drug baclofen 10mg oral baclofen 10mg uk
Thank you for your sharing. I am worried that I lack creative ideas. It is your article that makes me full of hope. Thank you. But, I have a question, can you help me?
메가 슬롯 사이트
그가 막 말하려고 할 때 Liu Jian과 다른 사람들이 돌진했습니다.