This is an implementation of a simple real-time API based on WebSockets where clients are subscribed to a specific channel and any JSON data can be pushed automatically to clients listening/subscribed to the channel. Clients define the channel they're subscribed to and there can be as many channels as required. Connections, scalability, fan-out and broadcasting are all automatically handled by the API.
The GraphQL API is defined in code where a GraphQL schema and API definition is generated programatically. Client code is also automatically generated. Hand coding GraphQL schema, queries, mutations, subscriptions is not required. If there's no need to leverage the built-in GraphQL strongly typed system, this pattern allows to send any data to connected/subscribed clients as long as it's in a valid JSON format.
- Create an AWS account if you do not already have one and log in. The IAM user that you use must have sufficient permissions to make necessary AWS service calls and manage AWS resources.
- Git installed
- Node and NPM installed
- AWS Cloud Development Kit (AWS CDK) installed
- Amplify CLI, only required to generate code as the backend deployment is done via AWS CDK
-
Clone the project to your local working directory:
git clone https://github.com/awsed/simpleWSAPI
-
Change the working directory to:
cd simpleWSAPI/cdk
-
Install the project dependencies:
npm install
-
Deploy the stack to your default AWS account and region. After deployment, the output of this command shows the GraphQL API endpoint, API ID, and API key. Take note of all the details as they'll be needed to setup the client:
cdk deploy
-
Change the working directory to the
client
folder:cd ../client
-
Install the project dependencies:
npm install
-
Open the file
src/App.js
and update the AppSync API congifuration details based on the output of the previouscdk deploy
. -
Define a name for your channel, as an optional step.
-
Generate the necessary code to interact with the API using the Amplify CodeGen with the API ID output of the previous
cdk deploy
. There's no need to create an Amplify CLI project, however you'll need to download the API schema from the AWS Appsync Console. Select the APIWS-API
in your account and, in the Schema section, select Export schema. Download and copy the schema file to the root of the/client
folder, where you need to execute the following command accepting all defaults:amplify add codegen --apiId xxxxxxxxxxxxxxxxxxxxxx
-
Execute the application and access it from multiple browser tabs/windows at http://localhost:3000 :
npm start
-
Send any valid JSON payload from one client and get it broadcasted in all browser windows. Since AWS AppSync automatically scales to demand, you can have thousands of clients broadcasting JSON data. You can also have multiple channels defined in different instances of the clients and confirm only clients subscribed to specific channels receive the JSON data.