Building Dynamic Applications with Lambda and GraphQL Subscriptions

Devaka Dabare
4 min readMay 31, 2023

--

Creating a real-time application involves building a system that can provide live updates and data synchronization to users in real-time. In this guide, we will walk through the steps to create such an application using a powerful combination of AWS Lambda, GraphQL subscriptions, React, and DynamoDB.

Step 01: Create DynamoDb

To create a DynamoDB table, login to the AWS Management Console, navigate to the DynamoDB service, and click on “Create table.” Provide a name for the table and specify the primary key, which can be a partition key or a composite key. Define the attribute names and data types for the table’s properties.

example dynamDB table with some data

Step 02: Create GraphQL API

To create a GraphQL API with DynamoDB as the data source using AWS AppSync, navigate to AppSync and select the Graph API option. Import DynamoDB as the GraphQL API Data Source and ensure you choose the correct table as the data source. In the next step, you can customize the GraphQL model by adding additional attributes as your ‘dynamo table’. Once done, you will have a GraphQL API with an auto-generated schema connected to DynamoDB, ready to power your application.

Step:03 Integrate with your app

To integrate your GraphQL API with your application, follow the instructions provided on the GraphQL homepage. These steps will guide you through the process of connecting your GraphQL API to your application seamlessly. By following these instructions, you can ensure smooth integration and leverage the power of GraphQL in your application.

Integration of GraphQL API

When configuring AWS Amplify in your local environment, it is important to grant the necessary permissions to your user in order to access Amplify effectively. In addition to assigning the AWSAmplifyFullAccess policy or creating custom policies, it is crucial to provide the AWSAppSyncFullAccess permission. This permission grants your user the necessary access to interact with AWS AppSync, including performing actions such as GetGraphqlApi and other operations related to your AppSync GraphQL API.

amplify add codegen --apiId yourGraphQL_appId

After running the above command you will get the files below.

Step:04 Create Lambda Function

In order to handle data addition and updates, a Lambda function can be utilized with the assistance of the AWS Amplify package and GraphQL mutations. By triggering a mutation, the Lambda function will automatically execute the necessary logic to add or update the data.

Moreover, the GraphQL subscription, which listens to this specific mutation, will be triggered simultaneously. As a result, any subscribed applications will receive real-time updates, ensuring that the newly added or updated data is broadcasted to all relevant subscribers.

This combination of Lambda functions, GraphQL mutations, and subscriptions enables seamless data management and real-time synchronization across multiple applications.

File Structure — Lambda

The example code as below :

const { API, graphqlOperation } = require('aws-amplify');
const { createExampleTable } = require('./graphql/mutations');

//configure appsync-amplify
API.configure({
"aws_appsync_graphqlEndpoint": "https://xxxxxxx.appsync-api.us-east-1.amazonaws.com/graphql",
"aws_appsync_region": "us-east-1",
"aws_appsync_authenticationType": "API_KEY",
"aws_appsync_apiKey": "da2-xxxxxxxxxxxx"
});

exports.handler = async (event) => {
try {
//graphql mutation variables
let variables = {
input: {
et_id: "1",
et_name: "TestName ",
et_colm1: "Test1",
et_colm2: "Test2",
et_colm1: "Test3",
et_colm3: true
}
};

//graphql mutation query
let mutation = graphqlOperation(createExampleTable, variables);

//execute mutation
const result = await API.graphql(mutation);

return {
statusCode: 200,
body: JSON.stringify(result)
}
} catch (error) {
console.log(error);
return {
statusCode: 500,
}
}
};

Step:04 Configure The Front end Application

To achieve similar functionality as the Lambda function, utilize the AWS Amplify package and configure it as described previously. Then, use the subscription query, such as onCreateExampleTable, with the API.graphql method from Amplify to subscribe to the desired events. This will enable real-time updates and data synchronization by handling the received subscription data in the next callback and handling any subscription errors in the error callback.

import { API, graphqlOperation } from 'aws-amplify';
import { onCreateExampleTable } from './graphql/subscriptions';

const subscribeToExampleTable = async () => {
try {
const subscriptionResult = await API.graphql(
graphqlOperation(onCreateExampleTable)
).subscribe({
next: (eventData) => {
console.log(eventData);
// Handle the subscription event data here
},
error: (errorData) => {
console.log(errorData);
// Handle any subscription errors here
}
});

// To unsubscribe from the subscription:
// subscriptionResult.unsubscribe();
} catch (error) {
console.error('Subscription Error:', error);
}
};

// Call the subscription function
subscribeToExampleTable();

In conclusion, programmers may design really dynamic and responsive applications by utilizing the strength of AWS Lambda and GraphQL subscriptions.

Now it’s your turn! Start implementing real-time features in your applications using Lambda and GraphQL subscriptions, and unleash the full potential of dynamic and engaging experiences for your users.

“Happy coding! :) ”

--

--

Devaka Dabare
Devaka Dabare

No responses yet