AMP for E-Commerce Part 3: Integrating the Entire Application with Alibaba Cloud ApsaraDB for MongoDB

本文涉及的产品
云数据库 MongoDB,独享型 2核8GB
推荐场景:
构建全方位客户视图
简介: In this three-part tutorial, we will explore how to create a fully functional e-commerce mobile application using AMP.

By Sai Sarath Chandra, Alibaba Cloud Tech Share Author and Alibaba Cloud MVP

This blog entry is a continuation of the article AMP for E-Commerce Part 2.

In our previous discussion, we have learned a lot about the AMP Framework, ECS Instances, and Alibaba Cloud ApsaraDB for MongoDB. Now you are familiar with all the products required, we will actually create a solution with all the pieces of all the amazing information available & will actually solve a real world scenario.

Overall Architecture

These are the pieces of solution we will work to achieve the below architecture

1

The above is a very simple architecture where a customer makes a request to the AMP Page via browser and it hits our ECS Instance which is running a webserver hosting the website/ webpages this AMP powered site internally uses the another application we created using Express JS on the node platform which connects to the Alibaba Cloud ApsaraDB for MongoDB makes the read request according to the client request and passes the data back very quickly then the node hosted API will pass the information back to the AMP Pages and then it will be used by the webpage to process and display the relevant information.

1.As we seen in the first tutorial, we have already created the Alibaba Cloud ApsaraDB for MongoDB in a very detailed way.
2.Now we are going to create the Node based API to fetch information from ApsaraDB for MongoDB.
3.We will also modify the Existing Open source Apache 2.0 AMP Template to suit our requirements. The reason we do this because of our precious time completing the whole design in the tutorial doesn’t meet the purpose. But I will go through the important part of the code and explain the same.
4.We will integrate the ApsaraDB for MongoDB with the AMP website to make it truly dynamical and we test the same.

Well, it’s time to get started.

Inserting Data onto the Database

Before we start creating and testing we need to insert some data onto the DB.

Software to be downloaded onto ECS

1.Visual Studio Code (preferably latest version)

  • To edit the code, this is the editor I use, you can switch to any favorite editor of yours

2.Google Chrome

  • We are going to use a plugin in chrome to keep this faster with the demo.

3.Web server plugin for chrome

4.ROBO 3T's - Studio 3T product.

  • This in my opinion is a very good product which provides GUI interactions with the MongoDB without compromising the ability to create and test Queries.

Uploading data onto ApsaraDB for MongoDB

1.Logon to the ECS Instance

2.Open Studio 3T product. You will be seeing something related to below screenshot

2

Click on connect then you will see the following window

3

I have already added the server, but I will show you how to add one, make sure you the "Connection String URI" from the ApsaraDB for MongoDB console. We will be connecting using this string

4

If you click on "New Connection" and selected the "From URI..", from the popup you will see an input box to enter the connection URI string.

Please make sure that you are entering the Connection URI String with your root password replaced at ****. If you do that correctly you will be seeing something related to this.

5

If you see something similar to the above screenshot then congratulations!! You have connected to the database.

Now we insert the data into MongoDB

Navigate to the "ExpressJS based API/json/" in the cloned code. I will show a sample insert into the database using Studio 3T.

For Example, I choose "high-low-accessories-products.json"

{
"name": "Chain set",
"description": "Silver alloy construction for durability.",
"price": 867,
"image": "/img/e-commerce/product/product-3.jpg",
"category": "accessories"
},
{
"name": "Red Cruiser",
"description": "Smooth ride for enjoyable cruising.",
"price": 688,
"image": "/img/e-commerce/product/product-6.jpg",
"category": "accessories"
},
{
"name": "Road Bike",
"description": "Built with lightweight aluminum for speed.",
"price": 644,
"image": "/img/e-commerce/product/product-9.jpg",
"category": "accessories"
},
{
"name": "Fixie Blue",
"description": "Designed to get you there.",
"price": 643,
"image": "/img/e-commerce/product/product-2.jpg",
"category": "accessories"
},
{
"name": "16-Speed",
"description": "Smooth shifting through all gears for city riding.",
"price": 524,
"image": "/img/e-commerce/product/product-5.jpg",
"category": "accessories"
},
{
"name": "Leather Saddle",
"description": "Firm, yet comfortable for long leisurely rides.",
"price": 476,
"image": "/img/e-commerce/product/product-4.jpg",
"category": "accessories"
}

Navigate to Studio 3T, expand the "admin" database and right click on the collections and select "Add Collection"

6

To reiterate collection is a group of information which you will be placing in this case this json structure. You will see the below screen.

7

We will give the name of the "high-low-accessories-products" without the extension .json and click on "Create". Then navigate to the collection

8

Switch to JSON View and copy paste the JSON provided. Just click of for the popups which come, as they basically say that the _id field is populated accordingly and the datatypes conversions also happens automatically. If everything happens successfully then you should see the following screen

9

Please go ahead and upload all the .json documents in the same fashion and you should see 8 collections as in the image shown above.

Creating & Testing Node-based Express API Accessing ApsaraDB for MongoDB

We will work on deploying an API which will interact to Alibaba Cloud's ApsaraDB for MongoDB for fetching the data as serve it to the front end.

For the sake of time, please go to the following link and clone the code

https://github.com/saichandu415/AMP-Ecommerce-Apsara/tree/master/ExpressJS%20based%20API

This is a very simple API, focusses only on the retrieving the data from the database.

Let me explain what the code is and what it does. The whole code is actually in the "app.js"

'use strict'

var express = require('express');
var formidable = require('formidable');
var uuid = require('node-uuid');
var https = require('https');
var fs = require('fs');
var sprintf = require("sprintf-js").sprintf;
var mongoClient = require('mongodb').MongoClient;
var dummyJson = require('./json/dummyvalue.json');

var app = express();


//code to enable https
var sslOptions = {
key: fs.readFileSync('./cert/key.pem'),
cert: fs.readFileSync('./cert/cert.pem'),
passphrase: 'saisarath'
};

//Mongo DB Instance Details
var host1 = "dds-6gj54086e0c157941.mongodb.ap-south-1.rds.aliyuncs.com";
var port1 = 3717;
var host2 = "dds-6gj54086e0c157942.mongodb.ap-south-1.rds.aliyuncs.com";
var port2 = 3717;
var username = "root";
var password = "Mongodb123";
var replSetName = "mgset-1050000641";
var demoDb = "admin";

var url = sprintf("mongodb://%s:%d,%s:%d/%s?replicaSet=%s", host1, port1, host2, port2, demoDb, replSetName);

console.info("url generated:", url);

app.get('/ampdemo/getData', function (req, res) {

//Headers to make AMP Accept
res.setHeader('AMP-Access-Control-Allow-Source-Origin','http://127.0.0.1:8000');
res.setHeader('Access-Control-Allow-Origin','http://127.0.0.1:8000');

console.log(JSON.stringify(req.query));

if (req.query && req.query.selection) {
//call promise and fetch data
var getData = fetchFromMongo(req.query.selection);
getData.then(function (dataFrmDB) {
//create response object
var response = {};
response.items = dataFrmDB;
res.status(200).json(response);
}, function (err) {
res.status(400).json(err);
});
} else {
res.status(400).json({ error: 'Please choose a selection' });
}
});


app.use('/', express.static('static'));

https.createServer(sslOptions, app).listen(443, function () {
console.log('Server for "Advanced Interactivity in AMP" codelab listening on port 443!');
});


function fetchFromMongo(collection) {

var coll2Fetch = collection;

return new Promise(function (resolve, reject) {
// Logic to fetch from the MongoDB
mongoClient.connect(url, function (err, db) {
//if error console error
console.log(err);
if (err) {
// Database not connected : error thrown
console.error("connect err:", err);
reject(err);
} else {
//Database connected successfully, get the DB Object
var adminDb = db.admin();
//Authenticate Database
adminDb.authenticate(username, password, function (err, result) {
if (err) {
console.log("authenticate err:", JSON.stringyfy(err));
reject(err);
} else {
console.log('Authenticated : ', JSON.stringify(result));
// Get the Collection handle.
var collection = db.collection(coll2Fetch);
collection.find({}).toArray(function (err, items) {
if (err) {
console.error('Unable to find data' + JSON.stringify(err));
} else {
console.info('data Fetched from MongoDB');
resolve(items);
}
});
}
});
}
});
});
}

sslOptions - You need to remember that AMP cannot talk on http protocols as it strictly prohibits the use of it. We created the certificate ourselves and included the same so the https will be enabled.

MongoDB Instance details – we update the mongoDB details here to get connected to the db instance through code with all the details of

Port – port number of the Node

Host – Host name of the Node

Username – user name of the ReplicaSet

Password – password assigned to the replica set during deployment

replicasetname – Replicasetname generated after the MongoDB instance deployment

DemoDb - The DB name you want to access to , most probably that would be admin considered to this demo.

Headers :

res.setHeader('AMP-Access-Control-Allow-Source-Origin','http://127.0.0.1:8000');
res.setHeader('Access-Control-Allow-Origin','http://127.0.0.1:8000');

These headers are very important because this says that you are saying to the API to access the cross domain requests. In prduction scenarios, please replace the localhost IP with the actual IP.

FetchFromMongo() :

This method is to fetch the data from MongoDB after several steps. Let's look into the steps to fetch the information from Alibaba Cloud ApsaraDB for MongoDB.

1.Get the query parameter from the request

  • We are eliminating the use of multiple URI's from the API end by using one endpoint and varying the information based on the query parameter

2.Get the mongoClient object

  • We have to get the instance of mongoClient object to perform the basic functionalities like authentication etc..

3.Get the database

  • Once the DB is connected. Point the Database you want to do operations on

4.Authenticate the DB

  • Perform the authentication step and get the full rights to the Database

5.Identify the collection

  • The Collection needs to be identified we would like to do the operation on, we are selecting the collection based on the query parameter

6.Operate and structure the collection Data

  • Once we found the data we need make operations on the data and restructure the data based on requirements

URI format
The URI should be "https://<host>:<port>/ampdemo/getData?selection=<collectionname>>"

Missing the selection parameter will throw the following error

400 Bad Request – Please choose a selection

Use HTTPS
AMP only accepts the https protocol so please make sure that the API you are deploying is exposed over https. This current API will work on the port 443 https enabled

How to run the API

If you are using visual studio then go to editor & press "CTRL + SHIFT + C" this will bring up the command prompt then you need to run command "node app.js"

If you are not using visual studio then you need to open command prompt from start menu & navigate to the corresponding folder using the "cd" command and then run the command "node app.js". In both cases if you done correctly then you should see something like below.

10

Then you can go ahead to browser and start invoking the API. Change the variable ECS_Internet_IP based on your actual IP address.

https://<ECS_Internet_IP>:443/ampdemo/getdata?selection=high-low-accessories-products

Since we are using the self-generated certificates, we should hit at least once in the browser and click on Add exception to accept the certificates in the system. In real world production scenario, you will see this will not be the issue because your certificate will be properly registered.

11

Once you add the security exception you should be able to see the information in your browser.

12

Congratulations!! You have successfully deployed your first API on an Alibaba Cloud ECS Instance.

AMP E-Commerce UI

Since this can be a complete tutorial by itself. Please go ahead and clone the existing repository we will start exploring how it is done and what we will apply the knowledge of the components we learnt so far.

Clone the following repository at the below link

https://github.com/saichandu415/AMP-Ecommerce-Apsara/tree/master/Website

Let me explain the snippets of code.

<div class="commerce-select-wrapper inline-block ">
<label for="price" class="bold caps h6 md-h7">Sort by:</label>
<select name="price" id="price" class="commerce-select h6 md-h7" on="change: AMP.setState({products: {filter: event.value}})">
<option value="high-low">Price: High-Low</option>
<option value="low-high">Price: Low-High</option>
</select>
</div>
</div>
</div>

<amp-list class="mx1 md-mxn1" [src]="'https://149.129.130.26:443/ampdemo/getData?selection=' + products.filter + '-' + products.category + '-products'" src="https://149.129.130.26:443/ampdemo/getData?selection=high-low-all-products" height="1000" width="300" layout="responsive">
<template type="amp-mustache">
<a href="product-details.amp.html" target="_self" class="commerce-listing-product text-decoration-none inline-block col-6 md-col-4 lg-col-3 px1 mb2 md-mb4 relative">
<div class="flex flex-column justify-between">
<div>
<amp-img class="commerce-listing-product-image mb2" src="{{image}}" width="340" height="340" layout="responsive" alt="{{ name }}" noloading=""><div placeholder="" class="commerce-loader"></div></amp-img>
<h2 class="commerce-listing-product-name h6">{{ name }}</h2>
{{ description }}
</div>
<div class="h6 mt1">&#163;{{ price }}</div>
</div>
</a>
</template>
</amp-list>

AMP uses http://basscss.com/ as their common CSS for most of their templates, but.

If you see this line of code in the <select> change: AMP.setState({products: {filter: event.value}}) Which shows the usage of the event listeners in AMP. Here you are listening to the change event and using AMP.setState construct you are assigning the event.value to the products products.filter key and we will use the same further to create adynamic query.

<amp-list class="mx1 md-mxn1" [src]="'https://149.129.130.26:443/ampdemo/getData?selection=' + products.filter + '-' + products.category + '-products'" src="https://149.129.130.26:443/ampdemo/getData?selection=high-low-all-products" height="1000" width="300" layout="responsive">

amp-list :
Fetches content dynamically from a CORS JSON endpoint and renders it using a supplied template.

It invokes the REST based endpoint and dynamically based on the user dropdown selection and assigns it to the amp-list which then generates the whole code based on the template.
<amp-img class="commerce-listing-product-image mb2" src="{{image}}" width="340" height="340" layout="responsive" alt="{{ name }}" noloading=""><div placeholder="" class="commerce-loader"></div></amp-img>

amp-img :
Here we use amp-img which uses the values/paths from the response and renders on to the template

One more thing to note in the previous example is that you need to keep your ECS Instance IP int eh [src] and src tags to make the template working.

You can also host the website using "Webserver for chrome",as it is very simple to use and host the site both locally and publically without any issue.

This is the download link for the chrome plugin

https://chrome.google.com/webstore/detail/web-server-for-chrome/ofhbbkphhbklhfoeikjpcbhemlocgigb/related?hl=en

Once you open the app in chrome you will be seeing something related to this

13

You need to select the folder you want to serve over the web. Then the webserver automatically restarts and gives an end point where you can test and make progress. This is not ideal for the real-time production scenarios but it makes the prototyping much faster.

Below are some screen shots how the website looks when you hit the endpoint

14

And this is the product listing page

15

Congratulations! You have deployed the application with the defined architecture.

Conclusion

I know it's a lot we went through the tutorials and you may also have some doubts. Please raise your concerns as issues to the github repo; I will do my best to answer them. Please take some time to read through and learn the required components. Going further these are some which help your work to become easier in a lot of ways. Please find the github link below:

https://github.com/saichandu415/AMP-Ecommerce-Apsara

相关实践学习
MongoDB数据库入门
MongoDB数据库入门实验。
快速掌握 MongoDB 数据库
本课程主要讲解MongoDB数据库的基本知识,包括MongoDB数据库的安装、配置、服务的启动、数据的CRUD操作函数使用、MongoDB索引的使用(唯一索引、地理索引、过期索引、全文索引等)、MapReduce操作实现、用户管理、Java对MongoDB的操作支持(基于2.x驱动与3.x驱动的完全讲解)。 通过学习此课程,读者将具备MongoDB数据库的开发能力,并且能够使用MongoDB进行项目开发。 &nbsp; 相关的阿里云产品:云数据库 MongoDB版 云数据库MongoDB版支持ReplicaSet和Sharding两种部署架构,具备安全审计,时间点备份等多项企业能力。在互联网、物联网、游戏、金融等领域被广泛采用。 云数据库MongoDB版(ApsaraDB for MongoDB)完全兼容MongoDB协议,基于飞天分布式系统和高可靠存储引擎,提供多节点高可用架构、弹性扩容、容灾、备份回滚、性能优化等解决方案。 产品详情: https://www.aliyun.com/product/mongodb
目录
相关文章
|
弹性计算 NoSQL 安全
AMP for E-Commerce Part 2: Creating Backend with Alibaba Cloud ApsaraDB for MongoDB
In this three-part tutorial, we will explore how to create a fully functional e-commerce mobile application using AMP.
1588 0
AMP for E-Commerce Part 2: Creating Backend with Alibaba Cloud ApsaraDB for MongoDB
|
JSON JavaScript NoSQL
Invoice Application Backend Using ApsaraDB for MongoDB
In part three of this three-part tutorial, we will explore how to create the backend of a fully functional invoice application using ApsaraDB for MongoDB.
2789 0
Invoice Application Backend Using ApsaraDB for MongoDB
|
1月前
|
存储 关系型数据库 MySQL
一个项目用5款数据库?MySQL、PostgreSQL、ClickHouse、MongoDB区别,适用场景
一个项目用5款数据库?MySQL、PostgreSQL、ClickHouse、MongoDB——特点、性能、扩展性、安全性、适用场景比较
|
2月前
|
存储 NoSQL 关系型数据库
非关系型数据库-MongoDB技术(二)
非关系型数据库-MongoDB技术(二)
|
2月前
|
NoSQL 关系型数据库 MongoDB
非关系型数据库-MongoDB技术(一)
非关系型数据库-MongoDB技术(一)
|
28天前
|
NoSQL Cloud Native atlas
探索云原生数据库:MongoDB Atlas 的实践与思考
【10月更文挑战第21天】本文探讨了MongoDB Atlas的核心特性、实践应用及对云原生数据库未来的思考。MongoDB Atlas作为MongoDB的云原生版本,提供全球分布式、完全托管、弹性伸缩和安全合规等优势,支持快速部署、数据全球化、自动化运维和灵活定价。文章还讨论了云原生数据库的未来趋势,如架构灵活性、智能化运维和混合云支持,并分享了实施MongoDB Atlas的最佳实践。
|
29天前
|
NoSQL Cloud Native atlas
探索云原生数据库:MongoDB Atlas 的实践与思考
【10月更文挑战第20天】本文探讨了MongoDB Atlas的核心特性、实践应用及对未来云原生数据库的思考。MongoDB Atlas作为云原生数据库服务,具备全球分布、完全托管、弹性伸缩和安全合规等优势,支持快速部署、数据全球化、自动化运维和灵活定价。文章还讨论了实施MongoDB Atlas的最佳实践和职业心得,展望了云原生数据库的发展趋势。
|
30天前
|
存储 NoSQL MongoDB
MongoDB 数据库引用
10月更文挑战第20天
19 1
|
1月前
|
存储 NoSQL Shell
MongoDB 创建数据库
10月更文挑战第12天
59 4
|
1月前
|
存储 NoSQL MongoDB
基于阿里云数据库MongoDB版,微财数科“又快又稳”服务超7000万客户
选择MongoDB主要基于其灵活的数据模型、高性能、高可用性、可扩展性、安全性和强大的分析能力。
下一篇
无影云桌面