msyinmei / platespace

A sample single-page application demonstrating MongoDB Stitch

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

platespace Stitch Sample Web Application

Requirements

In order to properly run this app on your local MacBook Pro or Linux machine, you need:

  • MongoDB 3.4.1 or above (required to restore the app sample dataset)
  • Node.js v6 or above
  • NPM v4.6.1 or above
  • Firefox 47 or above, Safari 10 or above (default on MacOS Sierra), Chrome 58 or above

Introduction

platespace is a sample web application built around a social, mobile, local restaurant search concept. It demonstrates how to use MongoDB Stitch as a backend-as-a-service and the MongoDB Stitch JavaScript SDK to perform data queries (such as inserting new data, paginating and sorting existing data)

Stitch Service Setup

  • Sign up with a new account at https://cloud.mongodb.com (or sign in with an existing MongoDB Cloud account).
  • You might be prompted to create a New Group Name. Enter any name, such as Stitch Clusters.
  • Build a new cluster (such as Stitch-Demo) if you don't have one yet.
  • If this is the first cluster in your Atlas group, scroll down to the bottom of the screen and set up the first cluster admin's username and password.
  • Once your cluster has been created, navigate to the ETL/restore folder and read the README file to restore the data set this application requires to your MongoDB Atlas cluster.
  • Select Stitch Apps in the left navigation menu.
  • Press the Create New Application button and name your application platespace (or any other name you wish). In the Link to Cluster section, select the cluster name you just selected.
  • Once your Stitch app has been created, you should be redirected to the Stitch Console at https://stitch.mongodb.com

In order to get our Stitch backend-as-a-service application fully set up, we must go through the following configuration steps:

  1. Set up the Stitch pipelines
  2. Set up the Stitch namespace rules (The name can only contain ASCII letters, numbers, underscores, and hyphens)
  3. Set up authentication (if any)
  4. Set up additional services (Amazon S3 and HTTP services)

Named pipelines

Stitch lets you define named pipelines. Named pipelines are custom pipeline requests that could be executed from the client side / by rules on top of the collections (see Rules section below). To create a named pipeline, select the Pipelines link in the left-hand menu and press the New button close to the Named Pipelines text.

geoNear pipeline

Paginated geoLocation pipeline * in the app we are paginating from the nearest restaurant (nearest to the CURRENT_LOCATION value in src/mongodb-manager/mongodb-manager.js).

Create a new pipeline with the following parameters:

  • Name: geoNear
  • Private: Disabled
  • Skip Rules: Enabled
  • Can Evaluate: Leave set to {}
  • Parameters:
    • longitude: Required
    • latitude: Required
    • query: NOT Required (leave disabled)
    • limit: Required
    • minDistance: Required
  • Output Type: Array
  • Service: mongodb-atlas
  • Action: aggregate
  • Value:
    {
      "database": "platespace",
      "collection": "restaurants",
      "pipeline": [
        {
          "$geoNear": {
            "near": {
              "coordinates": [
                "%%vars.longitude",
                "%%vars.latitude"
              ],
              "type": "Point"
            },
            "query": "%%vars.query",
            "limit": "%%vars.limit",
            "minDistance": "%%vars.minDistance",
            "distanceField": "dist",
            "spherical": true
          }
        }
      ]
    }
  • Bind data to %%vars:
{
 "longitude": "%%args.longitude",
 "latitude": "%%args.latitude",
 "query": "%%args.query",
 "limit": "%%args.limit",
 "minDistance": "%%args.minDistance"
}
  • Press the Done button.
  • Scroll up and at the top press the Save button.

userHasSingleReview pipeline

This pipeline is used by the Write permission of the platespace.reviewRatings namespace.

Add a new named pipeline and configure the following parameters:

  • Name: userHasSingleReview

  • Private: Disabled

  • Skip Rules: Disabled

  • Can Evaluate: Leave set to {}

  • Parameters:

    • userId: Required
    • restaurantId: Required
  • Output Type: Boolean

  • Service: mongodb-atlas

  • Action: aggregate

  • Value:

    {
      "database": "platespace",
      "collection": "reviewsRatings",
      "pipeline": [
        {
          "$match": {
            "owner_id": "%%vars.userId",
            "restaurantId": "%%vars.restaurantId"
          }
        },
        {
          "$count": "result"
        },
        {
          "$match": {
            "result": 1
          }
        }
      ]
    }
  • Bind data to %%vars:

    {
     "userId": "%%args.userId",
     "restaurantId": "%%args.restaurantId"
    }
  • Press the Done button.

  • Scroll up and at the top press the Save button.

aggregateRestaurant pipeline

Add a new pipeline named aggregateRestaurant and configure the following parameters:

  • Name: aggregateRestaurant
  • Private: Disabled
  • Skip Rules: Enabled
  • Can Evaluate: Leave set to {}
  • Parameters:
    • restaurantId: Required
  • Output type: Single Document
  • Service: mongodb-atlas
  • Action: aggregate
  • Value:
    {
      "database": "platespace",
      "collection": "reviewsRatings",
      "pipeline": [
        {
          "$match": {
            "restaurantId": "%%vars.restaurantId",
            "rate": {
              "$exists": true
            }
          }
        },
        {
          "$group": {
            "_id": "$restaurantId",
            "average": {
              "$avg": "$rate"
            },
            "count": {
              "$sum": 1
            }
          }
        }
      ]
    }
  • Bind data to %%vars:
    {
     "restaurantId": "%%args.restaurantId"
    }
  • Press the Done button.
  • Scroll up and at the top press the Save button.

updateRatings pipeline

This pipeline is called directly by the application's code when a user submits a review.

Add a new named pipeline and configure the following parameters:

  • Name: updateRatings
  • Private: Disabled
  • Skip Rules: Enabled
  • Can Evaluate: Leave set to {}
  • Parameters:
    • restaurantId: Required
  • Output type: Boolean
  • Service: mongodb-atlas
  • Action: update
  • Value:
    {
      "database": "platespace",
      "collection": "restaurants",
      "query": {
        "_id": "%%vars.restaurantId"
      },
      "update": {
        "$set": {
          "averageRating": "%%vars.pipelineResult.average",
          "numberOfRates": "%%vars.pipelineResult.count"
        }
      },
      "upsert": false,
      "multi": false
    }
  • Bind data to %%vars:
 {
   "restaurantId": "%%args.restaurantId",
   "pipelineResult": {
     "%pipeline": {
       "name": "aggregateRestaurant",
       "args": {
         "restaurantId": "%%args.restaurantId"
       }
     }
   }
 }
  • Press the Done button.
  • Scroll up and at the top press the Save button.

Rules configuration

Stitch lets you set up rules for every collection in your database, for instance user access rules or validation rules.

  • Select the mongodb-atlas service, navigate to the Rules tab and follow the steps below.

Restaurants collection rules

  • Press the New button and set the following parameters:
    • Database: platespace
    • Collection: restaurants
  • Press the Create button.
  • Select the newly created platespace.restaurants collection.
  • In the Filters tab, delete the default filter.
  • In the Field Rules tab, hover over the owner_id field and select the checkmark to delete it. Press OK to confirm.
  • In the Field Rules tab, select the Top-Level Document section and set the following Permissions:
    • Read: {}
    • Write: null (empty the field)
    • Valid: null
  • Press the SAVE button.

ReviewsRatings collection rules

  • Press the New button and set the following parameters:
    • Database: platespace
    • Collection: reviewsRatings
  • Press the Create button.
  • Select the newly created platespace.reviewsRatings collection.
  • In the Filters tab, delete the default filter.
  • In the Field Rules tab, select the Top-Level Document section and set the following Permissions::
    • Read: {}
    • Write:
    {
    "%and":
      [
        {
          "%%root.owner_id": "%%user.id"
        },
        {
          "%or": [
            {
              "%and": [
                {
                  "%%true": {
                    "%pipeline": {
                      "name": "userHasSingleReview",
                      "args": {
                        "userId": "%%user.id",
                        "restaurantId": "%%root.restaurantId"
                      }
                    }
                  }
                },
                {
                  "%%prevRoot": {
                    "%exists": true
                  }
                }
              ]
            },
            {
              "%and": [
                {
                  "%%false": {
                    "%pipeline": {
                      "name": "userHasSingleReview",
                      "args": {
                        "userId": "%%user.id",
                        "restaurantId": "%%root.restaurantId"
                      }
                    }
                  }
                },
                {
                  "%%prevRoot": {
                    "%exists": false
                  }
                }
              ]
            }
          ]
        }
      ]
    }
  • Leave the owner_id field as is.

Authentication

The platespace app supports anonymous authentication, but only in a limited fashion. Specifically, users have to be authenticated in order to be able to submit restaurant reviews. At this point, the application suppports anonymous access, Facebook and Email/Password Authentication.

Email/Password authentication

  1. In the Stitch Console page, navigate to Authentication and press the Edit button for the Email/Password option.
  2. In the Email Confirmation URL field, enter http://localhost:3000/#/confirm.
  3. In the Password Reset URL field, enter http://localhost:3000/#/reset and press Save.
  4. Navigate to the Users tab and click the Add User button.
  5. In the Email Address field, enter an email address such as gilfoyle@piedpiper.com.
  6. In the Password field, enter a password of your choice (longer than 6 characters).
  7. In the Confirm Password field, confirm the password you entered above.
  • Repeat steps 4 to 7 above to create additional named users.

You will use these users to connect to the application.

Facebook authentication

Facebook app setup
  • Navigation to the Facebook Developers site.
  • In the right-hand corner close to your name, select Add a New App
  • In the Display Name field, enter an app name such as PlateSpace (that name will be displayed to your users the first time they sign in with Facebook on your app) and press the Create App ID button.
  • The Select a Product page should be selected by default. If not, find the Add a Product link in the left navigation bar and select it.
  • Hover over the Facebook Login product and press the Set Up button.
  • In the Choose a Platform page, select www.
  • In the page that opens, fill out http://localhost:3000 in the Site URL text box and press Save. Then press Continue.
  • Leave this page and in the left navigation bar, select Settings right under Facebook Login.
  • Add the following entry in Valid OAuth Redirect URIs text box: https://stitch.mongodb.com/api/client/v1.0/auth/callback and press Save Changes at the bottom.
  • In the left navigation bar, select Settings right under Dashboard and copy the App ID and App Secret values to a text file.
Stitch Facebook authentication setup
  • In the Stitch Console page, navigate to Authentication and press the Edit button for the Facebook option.
  • In the Client ID field, enter your Facebook App ID value.
  • In the Client Secret field, enter your Facebook App Secret value.
  • In the Redirect URIs section, add http://localhost:3000/ (don't forget the last trailing slash).
  • In the Metadata Fields section, select the name checkbox.

Amazon Web Services and Stich S3 Setup

Important Note: This section requires that you have an AWS account with IAM full access permissions and S3 full access permissions.

Amazon Web Service configuration

Find your keypair information in Web/temp-key-aws.txt Your pre-created bucket for this tutorial is named platespace-demo

For today we've provided you a keypair and a bucket for your images. If you were to create this on your own you would:

  • Sign in to your AWS account
  • Navigate to the IAM->Users section
  • Add a user (for instance s3.stitchuser) with Programmatic access as the access type
  • Press Next:Permissions, select Attach existing policies directly and select the AmazonS3FullAccess policy
  • Press Next: Review and Create user
  • In the final screen, copy the Access key ID and the Secret access key values to a text file
  • Navigate to Amazon S3 and create a bucket. Store your bucket name in the same text file as the IAM credentials above

Stitch S3 Service configuration

  • Sign in to the MongoDB Stitch console and press the Add Service button in the Services section of the left navigation menu.
  • Select the S3 service, name it UploadToS3 and press the Add service button.
  • In the Config tab, select the AWS region where your bucket is located and set the Access Key ID and Secret Access Key text boxes to the values you stored in the text file above and press Save. Important Note: if you want to select the us-east-1 region, make sure you select another region first and then the us-east-1 region again.
  • Select the Rules tab and press the Add Rule button.
  • Check the put action and in the When text area, enter the following JSON:
    {
    "bucket": "%NAME_OF_YOUR_BUCKET%"
    }
  • Replace %NAME_OF_YOUR_BUCKET% with the name of the bucket you previously created (without any percent sign).
  • Press Save.

Clarifai Service Setup

Clarifai Token

The first step is to retrieve a valid Bearer token from Clarifai.

  • To do so, navigate to https://developer.clarifai.com/signup and sign up to create a Clarifai account.
  • After you sign in on Clarifai's developer portal, click on your name at the top.
  • In Applications, select My First Application and update its name.
  • Scroll down and in the Access Tokens section, press the Generate Access Token button.
  • Copy the access token and press Save Changes.

Stitch HTTP Service Setup

  • Sign in to the MongoDB Stitch console and press the Add Service button in the Services section of the left nav menu.
  • Select the HTTP service, name it Clarifai and press the Add service button.
  • Select the Rules tab and press the Add Rule button.
  • Check the post checkbox in the Actions list
  • In the When text area, enter the following value:
      {
      "%%args.url.host": {
        "%in": [
          "api.clarifai.com"
        ]
      }
    }

processImage Stitch Pipeline Setup

The application needs a pipeline to be able to call the Clarifai HTTP service with the proper format and parameters.

Select the Pipelines link in the left-hand menu add press the New button. Then enter the following values:

  • Name: processImage
  • Private: Disabled
  • Skip Rules: Enabled
  • Can Evaluate: Leave set to {}
  • Parameters:
    • imagePublicUrl: Required
  • Output type: Single Document
  • Service: {the Clarifai service}
  • Action: post
  • Value:
    {
      "url": "https://api.clarifai.com/v2/models/aaa03c23b3724a16a56b629203edc62c/outputs",
      "headers": {
        "Authorization": [
          "Bearer mqE59AWPDOoHwRMtXFHWxmhuLBS9oE"
        ]
      },
      "body": {
        "inputs": [
          {
            "data": {
              "image": {
                "url": "%%vars.imageUrl"
              }
            }
          }
        ]
      }
    }
    Important note: You should update the NhDj1HG5bqC9SEhhvr0GC8qFN6Znc1 value above with your own Clarifai Access Token.
  • Bind data to %%vars:
 {
   "imageUrl": "%%args.imagePublicUrl"
 }
  • Press the Done button.
  • Scroll up and at the top press the Save button.

Application Setup

  • Clone this repository and open a Terminal console on the Web folder
  • Run npm install or yarn install to install dependencies.
  • Edit the src/config.js file and customize the following paramaters depending on your MongoDB Stitch configuration:
    • STITCH_APP_ID: The app id can be found on Stitch Dashboard, in the Clients page of the left menu.
    • MONGODB_SERVICE_NAME: The MongoDB service name can be found on Stitch Dashboard. The default value is mongodb-atlas and shouldn't have to be updated
    • DB_NAME: The database name as defined in the MongoDB Atlas cluster. Should be left to platespace.
    • CURRENT_LOCATION: The longitude/latitude coordinates used as the (hardcoded) user location. Currently set to Hyatt Regency hotel in Chicago.
    • S3_SERVICE_NAME: Name of the AWS S3 service name as set in the Stitch console. Should be left to the default value of UploadToS3.
    • (Optional) S3_BUCKET: The name of the AWS S3 bucket you configured above in the Stitch S3 Service Rules section. Update to your own bucket name if you're using your own AWS S3 service.

Test the application

  • To start the development server and to launch the app, run yarn start or npm start.
  • The default browser should open a page at http://localhost:3000.
  • Sign in using one the named users you previously created in the Email/Password Authentication section above.
  • You are redirected to the list of restaurants (generated thanks to the geoNear pipeline).
  • Select a restaurant and in the Reviews section, press the Add button to enter a new review.
  • Enter the comment of your choice, choose a rating and select an image from the Web/src/resources folder.

Application Architecture

Database collections and schemas used in app

  • reviewsRatings collection:

    {
      "_id": <ObjectId>,
      "owner_id": <String>,
      "restaurantId": <ObjectId>,
      "nameOfCommenter": <String>,
      "comment": <String>,
      "rate": <Integer>,
      "dateOfComment": <Date>,
      "imageUrl": <String>,
      "imageRecognitionData": <String>
    
    }
  • restaurants collection:

  {
    "_id": <ObjectId>,
    "name": <String>,
    "address": <String>,
    "phone": <String>,
    "Image_url": <String>,
    "website": <String>,
    "averageRating": <Double>,
    "numberOfRates": <Double>,
    "openingHours": {
      "end": <String>,
      "start": <String>
    },
    "attributes": {
      "veganFriendly": <Boolean>,
      "openOnWeekends": <Boolean>,
      "hasParking": <Boolean>,
      "hasWifi": <Boolean>
    },
    "location": {
      "coordinates": [
        <Double>, // "longitude"
        <Double> // "latitude"
      ],
      "type": "Point"
    }
  }

About

A sample single-page application demonstrating MongoDB Stitch

License:MIT License


Languages

Language:JavaScript 97.8%Language:HTML 0.9%Language:CSS 0.9%Language:Shell 0.3%