Creating Lambda function to call GraphQL on App Sync(AWS)

  1. A function called by Cognito, which is a managed service on AWS to authenticate users that the function can listen for authentication actions.
  2. A function called by DynamoDB that can listen to database changes.(the function can take old and new records)
  3. A function called by a scheduled trigger that allows the function to be called automatically at a specific time or called periodically.

Create a function on local environment

Create a function locally

mkdir lambdaFunctionTest
cd lambdaFunctionTest
yarn
touch index.js

Install packages

yarn add aws-appsync
yarn add graphql-tag
yarn add isomorphic-fetch

Write code

const AWSAppSyncClient = require("aws-appsync").default;
const gql = require("graphql-tag");
require("isomorphic-fetch");
const env = require("process").env;
const region = env.AWS_REGION;
const appSyncUrl = env.ENDPOINT;
const apiKey = env.API_KEY;
exports.handler = async event => {

const appSyncClient = new AWSAppSyncClient({
url: appSyncUrl,
region,
auth: {
type: "API_KEY",
apiKey
},
disableOffline: true
});
const variables = {
//Write mutation's input
}
const mutation = gql`
mutation{
//Whatever you want to do
}`;
try {
const result = await appSyncClient.mutate({
variables,
mutation
});
//When mutation succeeded
console.log("success", result);
} catch (err) {
//When mutation failed
console.log(err);
}
};

Explain code

const AWSAppSyncClient = require("aws-appsync").default;
const gql = require("graphql-tag");
require("isomorphic-fetch");
const env = require("process").env;
const region = env.AWS_REGION;
const appSyncUrl = env.ENDPOINT;
const apiKey = env.API_KEY;
exports.handler = async event => {}

Test locally

exports.handler();
const event = {} //Something
const context = {} //Something
const callback = (() => {//Something})
exports.handler(event, context, callback);
node ./index.js

Deploy to Lambda

Compress file

Create a function on AWS Lambda

Upload to Lambda

Configure function

Create role to call App Sync

Set environmental variable

Test our function

Set triggers

User authentication (Cognito) trigger

DynamoDB change trigger

Time scheduled trigger

cron(1 0 * * ? *)

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store