Skip to content
This repository has been archived by the owner on Jun 3, 2020. It is now read-only.

Unicorn Loyalty: E-Commerce Serverless GraphQL Loyalty Sample App

License

Notifications You must be signed in to change notification settings

amazon-archives/aws-serverless-appsync-loyalty

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

43 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Unicorn Loyalty: E-Commerce Serverless GraphQL Loyalty Sample App

Unicorn Loyalty is a new startup that provides fantastic unicorns for customers. The business just started and it's giving away 1000 Unicoin Points for new customers to purchase the unicorns available on inventory.

(Live Coding walk-through video covering Lambda and AppSync manual setup available on https://www.youtube.com/watch?v=WOQIqRVzkas or https://www.twitch.tv/videos/288401222)

Behind the Scenes

Architecture

  • AWS AppSync
  • AWS Lambda
  • Amazon DynamoDB
  • Amazon Cognito User Pools
  • Amazon Pinpoint
  • No Servers!

Prerequisites

Optional

  • AWS Cloud9 : We assume you are using Cloud9 to build this application. You can optionally choose to use any IDE/Text Editor such as Atom or VS Code, in that case you should use the AWS SAM CLI to deploy Lambda and the DynamoDB tables.

Initial Setup - Mobile CLI and Amplify

Create a Cloud 9 environment and execute:

$ create-react-app unicorn-loyalty
$ cd unicorn-loyalty

Install and use the latest LTS Node version:

$ nvm i v8

Set up your AWS resources with the AWS Mobile CLI:

$ awsmobile init

Chose the default options, make sure you are logged in with a user that has administrator access and click the resulting link to create an IAM user for the Mobile CLI by selecting OPEN:

Mobile CLI Setup

Follow the steps in the IAM Console with default options then use the generated credentials to configure the access in the Mobile CLI:

Mobile CLI Permissions

Now let's add the features we need for our application (User Sign In, Analytics, Hosting and AppSync):

Mobile CLI Features

Execute the following command to commit the changes:

$ awsmobile push

To test if everything is working, open App.js and let's add 4 extra lines of code to add AuthN/Z with MFA (withAuthenticator HOC). Replace the existing code with:

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import Amplify from 'aws-amplify';
import { withAuthenticator } from 'aws-amplify-react';
import aws_exports from './aws-exports'; // specify the location of aws-exports.js file on your project
Amplify.configure(aws_exports);

class App extends Component {
  render() {
    return (
      <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h1 className="App-title">Welcome to React</h1>
        </header>
        <p className="App-intro">
          To get started, edit <code>src/App.js</code> and save to reload.
        </p>
      </div>
    );
  }
}

export default withAuthenticator(App, { includeGreetings: true });

Now execute:

$ awsmobile run

Then click on PREVIEW -> PREVIEW RUNNING APPLICATION on Cloud9 and sign up a user:

Mobile CLI Features

Download all files from the Github repo. Upload them to your Cloud9 workspace (FILE -> UPLOAD LOCAL FILES), overwriting the files in the local React app folder:

Uploading Files

Lambda Setup

From Cloud9 select the AWS Resources tab on the right, you'll find a local Lambda funcion under the sam folder called UnicornLoyalty. Right click and select EDIT CONFIG to check the related SAM template and EDIT FUNCTION to check the Lambda code:

Lambda SAM Config

By default the 1000 Unicoins give away special is valid until the last day of 2018. Edit the expiry date accordingly if you want to modify the deadline:

let expiry = new Date('2018.12.31').getTime() / 1000; 

On the same menu click DEPLOY (or execute sam package/deploy with the SAM CLI it you're not on Cloud9). The SAM Template will deploy a Lambda function and 3 DynamoDB tables. Lambda will interact directly with the Users table by detecting newly registered users to make sure they will only get the 1000 Unicoin Points special before the expiry date as well as manage and update the user unicoins/points balance when a order is placed. The other tables will be used directly by AppSync.

AppSync Setup

The Mobile CLI creates a sample Event API on AppSync by default. We wont use that. Go to the AppSync console and paste the contents of the file appsync/schema.graphql in the SCHEMA setion:

GraphQL Schema

Go to DATA SOURCES, delete the 2 tables from the sample. Now create 3 data sources as follows, pointing to the Items and Orders tables and the Lambda function created earlier :

AppSync Data Sources

Back to Cloud9, execute the following command to retrieve the AppSync changes:

$ awsmobile pull

Go to the folder awsmobilejs/backend/appsync and delete the file resolvers.json and the folder resolver-mappings.

Now go to the folder appsync in the root of the application directory and copy the file resolvers.json and the folder resolver-mappings to the previous folder awsmobilejs/backend/appsync, replacing the deleted files.

Next step is to configure AppSync authentication. Execute the following command and select the options:

$ awsmobile appsync configure

? Please specify the auth type:  AMAZON_COGNITO_USER_POOLS
? user pool id:  <User Pools ID>
? region:  <Region>
? default action:  ALLOW

Execute the following command to commit the changes:

$ awsmobile push

Creating Some Unicorns

Open the file src/aws-exports.js generated by the Mobile CLI and copy the value of the key "aws_user_pools_web_client_id"to retrieve the App Client ID the Cognito User Pools is using to authenticate AppSync calls.

Go to the AppSync console and select the QUERY section. Click LOGIN WITH USER POOLS, use the client ID you just retrieved from aws-exports.js and the credentials from the user you signed up earlier. You'll also need to provide a MFA code.

Execute the following GraphQL operation (mutation) to create your first Unicorn:

mutation {
  addInventory(itemDescription: "Amazing Unicorn", price: 50){
    itemId
    itemDescription
    price
  }
}

Create as many Unicorns as you'd like by changing the values. Going to the DynamoDB console, you can confirm the Unicorns were created successfully:

Unicorns on DynamoDB

Welcome to the Unicorn Loyalty Shop

Back to Cloud9 execute:

$ awsmobile run

(In case of errors or missing packages, you might need to run npm install and try again)

Then click on PREVIEW -> PREVIEW RUNNING APPLICATION to access the Unicorn Loyalty App:

Unicorn Loyalty Shop - Preview

Finally you can publish to CloudFront and S3 with a single command:

$ awsmobile publish

It will automatically make the Unicorn Loyalty app available in a powerful and reliable global content delivery network backed by a S3 website:

Unicorn Loyalty Shop - Prod

You can get Analitycs about usage and revenue from Amazon Pinpoint, all thanks to a couple of lines of code required by the AWS Amplify Analytics component and the to the Pinpoint Project AWS Mobile CLI creates by default:

Analytics.record({
    name: 'unicornsPurchase', 
    attributes: {}, 
    metrics: { totalOrder: order.totalOrder }
});
Analytics.record('_monetization.purchase', {
    _currency: 'USD',
    _product_id: order.itemId,
    }, {
    _item_price: order.unitPrice,
    _quantity: order.count,
})
  • Usage Data: Unicorn Analytics

  • Revenue Data: Unicorn Analytics

Feel like a challenge? What's next?

We added the backend logic to get all orders from the current user:

query {
  getMyOrders{
    orderId
    itemId
    count
    date
    totalOrder
  }
}

Alternatively, you can get the same result using the relation between the User type (Users Table) and the Order type (Orders Table) by querying the User ID:

query {
  getMe(userId:"<User ID Here>"){
    orders{
        orderId
    }
  }
}

We also added the backend logic to get the items in a specific order by querying the Order ID:

query {
  getOrder(orderId:"<Order ID Here>"){
    orderId
    itemId
    count
    date
    totalOrder
  }
}

Using AWS Amplify implement a new feature to the Unicorn Loyalty app so users can get information on all the orders they placed as well as Unicorns that were purchased in a previous order. Bonus points if implemented with the built-in pagination support.

Go Build with Serverless GraphQL!

License Summary

This sample code is made available under a modified MIT license. See the LICENSE file.

Releases

No releases published

Packages

No packages published

Contributors 4

  •  
  •  
  •  
  •