Giter Club home page Giter Club logo

aws-serverless-appsync-loyalty's Introduction

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.

aws-serverless-appsync-loyalty's People

Contributors

awsed avatar chriscoombs avatar hyandell avatar rkrol avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

aws-serverless-appsync-loyalty's Issues

Cannot register a new user using GUI

No errors, it goes to Confirm Code, even Re-send code sends nothing to email.
Has this app been tested ? I can provide a public URL if someone wants to check it out.

Unable to add Unicorn to user

From the AppSync console I successfully logged in with the new user id & pool etc, but when I look up the corresponding item in the dynamoDB table, I dont see anything that ties it to a user.

And the users table is empty

Why use AWS Mobile?

AWS Amplify is the next generation of AWS Mobile so why still use AWS Mobile?

how to identify no of active subscribers by subscription

Need to keep count of how many subscribers are connected with each subscription.

For UserA, UserB are connected with SubscriptionA : then 2 is the total subscribers
For UserA are connected with SubscriptionB : then 1 is the total subscribers

Can i know when UserA unsubscribes , subscribes, disconnects, reconnects from AppSync ?

Pull generates errors from starter app

This is obviously a remnant of the starter app, but I am unable to pinpoint the cause, I think it is in the cloud (aws) and some clean up needs to take place there.

ec2-user:~/environment/unicorn-loyalty $ awsmobile pull

retrieving the latest backend awsmobile project information
awsmobile project's details logged at:
awsmobilejs/#current-backend-info/backend-details.json
awsmobile project's specifications logged at:
awsmobilejs/#current-backend-info/mobile-hub-project.yml
โ ™ retrieving appsync: get data sources...Failed to create dynamoDB table AppSyncEventTable-QmyfsE1o
{ ResourceNotFoundException: Requested resource not found: Table: AppSyncEventTable-QmyfsE1o not found
at Request.extractError (/home/ec2-user/.nvm/versions/node/v8.11.4/lib/node_modules/awsmobile-cli/node_modules/aws-sdk/lib/protocol/json.js:48:27)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.