Introduction: EMAS Serverless is a sub-product of Alibaba Cloud's one-stop application R&D platform EMAS. It is a serverless development and operation suite provided for small program scenarios. Developers do not need to care about servers and the operation and maintenance of underlying facilities, and focus on code logic With the business itself, it has the advantages of minimal operation and maintenance, multi-terminal adaptation, on-demand use, elastic expansion, etc., helping developers to quickly deploy small programs. This article will give you a comprehensive understanding of EMAS Serverless applet development, and the e-book "Five Days of Fun" is attached. EMAS Serverless is a free download! !

\>> Come and download for free|E-book "Five Days to Play with EMAS Serverless" <<

Click to download for free

"Five days to play EMAS Serverless"

What is EMAS Serverless

EMAS Serverless is a one-stop back-end development platform based on serverless technology provided by Alibaba Cloud. It provides developers with highly available and elastically scalable cloud development services, including cloud functions, cloud databases, cloud storage, static website hosting and other functions. Developers and enterprise customers can quickly build a cloud and multi-terminal application, and you can seamlessly connect to rich cloud resources without managing infrastructure such as servers.

 title=

Figure 1 EMAS Serverless product architecture

EMAS Serverless Application Scenario

ES supports cloud functions, cloud databases, cloud storage and other capabilities, and has three characteristics of elastic scaling, pay-as-you-go, and free operation and maintenance. Elastic scaling saves you from frequent operation and maintenance of scaling machines, and easily responds to various traffic emergencies, saving you a lot of time. Pay- as-you-go pays as much as you use, and function billing is accurate to milliseconds, saving you a lot of money. Free operation and maintenance allows developers to focus on more valuable business logic instead of spending more energy on underlying resources such as servers. Therefore, ES is widely used in e-commerce, consulting, tourism, corporate display, community, restaurant and other industry scenarios.

 title=

Figure 2 EMAS Serverless application scenario

open product

First open the EMAS Alibaba Cloud console: [https://emas.console.aliyun.com](https://emas.console.aliyun.com) , create a new project and enter it. Then select Platform Services and create a service space. As shown in Figure 3 and Figure 4:

 title=

Figure 3 EMAS console home page - project management

 title=

Figure 4 Select the platform service and create a service space

Billing method

Support pay-as-you-go and annual and monthly payment methods.

  • Pay-As-You-Go (Postpaid): A postpaid model where you use it first and pay later. Generally, it is suitable for applications or services with explosive business volume.
  • Yearly subscription (prepaid): A prepaid model that pays first and then uses it. By subscribing yearly and monthly, you can reserve resources in advance and enjoy greater price concessions, helping you to save money to a greater extent.

pay-as-you-go

<span>Module</span> <span>Billing items</span> <span>Unit price (pay-as-you-go)</span>
<span>Cloud function</span> <span>Resource usage (GBs)</span> <span>0.000110592</span>
<span>Number of calls (10,000 times)</span> <span>0.0133</span>
<span>Outgoing network traffic (GB)</span> <span>0.8</span>
<span>Cloud Database</span> <span>Capacity (GB/day)</span> <span>0.07</span>
<span>Number of read operations (10,000 times)</span> <span>0.015</span>
<span>Number of write operations (10,000 times)</span> <span>0.05</span>
<span>Cloud Storage</span> <span>Capacity (GB/day)</span> <span>0.0043</span>
<span>Number of download operations (10,000 times)</span> <span>0.01</span>
<span>Number of upload operations (10,000 times)</span> <span>0.01</span>
<span>CDN Traffic (GB)</span> <span>0.18</span>
<span>Static website hosting</span> <span>Capacity (GB/day)</span> <span>0.0043</span>
<span>CDN Traffic (GB)</span> <span>0.18</span>
### Yearly and monthly
<span>Package Specifications</span> <span>Price (yuan/month)</span> <span>Package description</span>
<span>Developer Edition</span> <span>Free</span> <span>Suitable for practice, project development, and initial use. </span>
<span>Basic Edition</span> <span>5</span> <span>We provide packages of various specifications, you can choose according to your needs based on business scale and project development stage, and upgrade packages as your business grows. </span>
<span>Standard Edition</span> <span>24</span>
<span>Pro Edition</span> <span>82</span>
<span>Enterprise Edition</span> <span>316</span>
<span>Ultimate Edition</span> <span>688</span>
For specific package resources, please refer to https://help.aliyun.com/document\_detail/435837.html ## Installing the SDK We take the development of Alipay applet as an example to demonstrate how to quickly develop and deploy with ES capabilities. 1. First run the following command in the root directory of the applet project. ` npm install --save @alicloud/mpserverless-sdk ` or Alipay applet has some special configuration, please refer to: https://help.aliyun.com/ document\_detail/444395.html ## Initializing the SDK Before starting to use the serverless service on the applet side, you need to call the mpserverless.init method to complete the initialization of the service, and it can only be initialized once. The more common practice is to initialize the onLaunch life cycle, and mount the instance object mpserverless to the global object of the App , so that the subsequent called in other files. This demonstration uses anonymous initialization . This initialization method does not need to configure keys on the Alipay open platform, but at the same time, it is impossible to obtain the identity of the applet user. For more details, please refer to: https://help.aliyun.com/document\_detail/444402.html ` // app.js import MPServerless from '@alicloud/mpserverless-sdk' const mpserverless = new MPServerless(my, { appId: 'Mini Program AppID', spaceId: 'Service Space SpaceId', clientSecret: 'Service Space Secret', endpoint: 'Service Space API Endpoint' }); App({ mpserverless: mpserverless, onLaunch() { mpserverless.init( authorType: 'anonymous' ); }, }); ` ## Cloud Function Cloud Function (FaaS) is a piece of cloud running, lightweight, unrelated and reusable code. No need to manage the server, just write and upload the code, you can get the corresponding data results. The cloud function has only one input parameter ctx object, and the output parameter structure is defined by the developer: ` // The cloud function entrance is defined in index.js module.exports = async ctx = > { // do something return result } ` ### ctx object structure
<span>Field</span> <span>Type</span> <span>Meaning</span>
ctx.args Object? The parameter body passed in when the developer calls the cloud function through the SDK. For example: mpserverless.function.invoke( 'function-name', args ) The input parameter structure of HTTP trigger and scheduled task trigger is slightly different, please refer to the official documentation.
ctx.logger function Log tool, you can print <span> different types of log information, and then view the execution log in the cloud function console. </span><ul><li><span>info</span></li><li><span>warn</span></li><li><span>error</span></ li><li><span>debug</span></li></ul>
ctx.mpserverless SDK The cloud function provides you with the initialized mpserverless object, so that you can continue to call other basic services of Serverless. The usage of <span>API is basically the same as that of the client. </span>
ctx.env Object <span>In the cloud function, use </span> <span>ctx.env</span> <span> to obtain environment parameters, such as SpaceId, calling source, client source IP and client UserAgent and other information. </span><ul><li> <span>MP_SPACE_ID</span> <span>Service Space ID</span></li><li> MP_SOURCE Call Source</li></ul ><ul><li><ul><li> server : Server trigger</li><li> function : Cloud function trigger</li><li> client : Client trigger</li><li> http : HTTP trigger</li><li> timing </li> ul></li></ul><ul><li> MP_USER_AGENT client flag, only calls from client include this field</li><li> MP_CLIENT_IP client Client IP, only calls from the client include this field</li><li> MP_APP_ID AppId of the applet, the client will call the cloud function after non-anonymous authorization to include this field</li></ul>
ctx.httpclient HttpClient Any HTTP and HTTPS protocol web services can be requested through this object. For example: ctx.httpclient.request('https:// * ')
### Development, deployment and debugging Let's take the development of a cloud function TwoNumOperation as an example: ` // index.js module.exports = async ctx => { const { action, x, y } = ctx.args; let result = 0 switch (action) { case '+': result = x + y; break; case '-': result = x - y; break; case ' ': result = x y; break; case '/': if (y === 0) { throw new Error('cannot divide by 0') } result = x / y; break; default: throw new Error(' not support action ' + action) } return { result } } ` Create a new folder TwoNumOperation , then create a new file index.js under the folder and put the above code, and then package it as a whole This folder gets the compressed file TwoNumOperation.zip. As shown in Figure 5 below:  title= Figure 5 Cloud function code package As shown in Figure 6 below, first we create a new cloud function TwoNumOperation in the Alibaba Cloud console. The function name must be the same as the folder name . Then upload and deploy the compressed code package. After the deployment is successful, you can test and run it on the console, click the code to execute, and enter the function execution parameters to run the cloud function. Click the log to view the execution log of the cloud function, which is convenient for developers to debug.  title= Figure 6 Cloud function deployment, execution, log viewing ### Call cloud function in applet As shown in Figure 7, call cloud function in applet. index.axml layout file simply writes a form with three inputs, and binds the form submit function invokeFunction . index.js文件首先从全局导入mpserverless e7a0048f26580d1b0a0c14f47cb3cc6c---对象,然后在表单提交函数中获取参数actionxy , and then call the cloud function through mpserverless.function.invoke .  title= Figure 7 Calling cloud functions in the applet ## ApsaraDB for cloud database service is a database hosted in the cloud based on MongoDB, and the data is stored in JSON format. As a developer, you can read and write data through the mpserverless object in the client or cloud functions. ` mpserverless.db.collection('user').findOne( { name: 'Zhang San' } ) ` ### Compared with MySQL, ES cloud database service uses the underlying MongoDB, which stores data in JSON format. Each record in the database is a document in JSON format. A database can contain multiple collections (equivalent to tables in relational databases), and each collection can be regarded as an array of JSON documents. The comparison between MongoDB database and relational database MySQL is shown in the following table.
<span>Cloud Database (MongoDB)</span> <span>Relational database (MySQL)</span>
<span>Database</span> <span>Database</span>
<span>Table (collection)</span> <span>Table</span>
<span>document</span> <span>row (row)</span>
<span>field</span> <span>column</span>
<span>index</span> <span>index</span>
<span>Automatically use the </span><span>_id</span><span> field as the primary key</span> <span>primary key</span>
### Data Structure Design Strategy MongoDB is a NoSQL database based on distributed file storage, which aims to provide a scalable and high-performance data storage solution for WEB applications. Take an e-commerce platform as an example. Usually, the core data of an e-commerce platform includes products, users, shopping carts and orders. An order is generated by a user purchasing a product, and an order can be considered to be generated by the relationship between the product and the user. Before the order is generated, the relationship between the product and the user is maintained through the shopping cart. For the above case, a product table named products can be designed to store the following information: * Basic product information: including display information, product specifications, etc. * Attribute information: attributes belong to a product and belong to an N-to-1 relationship. Therefore, it is more appropriate to store it in the products collection as a sub-document ; * Inventory and price information: Inventory is not only associated with products, but also directly corresponds to product attributes. Therefore it should also be placed in the products collection; ` { "id": 5573, "name": "Egg T-shirt", "desc": { "short": "Limited Edition Egg T-shirt, wear You are not far from being a geek on it", "long": "This is a very long description", "category": { "_id": "48bf43a..29e90bc", "name": "Tops" } }, "attributes": [ { "id": 1151, "name": "size", "values": [ { "id": 3871, "value": "S" }, { "id": 3874, "value": "M" }, { "id": 3875, "value": "L" } ] }, { "id": 1152, "name": "gender", "values": [ { "id ": 3872, "value": "Male" }, { "id": 3873, "value": "Female" } ] } ], "sku": [ { "id": 1153, "stock": 30, "attributeIds": [ 3871, 3872 ], "attributes": [ { "key": "size", "value": "S" }, { "key": "gender", "value": "female" } ] } ] } ` ### Create a data table Click "+" on the Alibaba Cloud console to create a new data table  title= Figure 8 Create a new data table in the console ### Add data records#### insertOne Insert user Zhang San ` mpserverless.db.collection('users').insertOne( { name: 'Zhang San' , age: 18 } ) ` #### insertMany ` mpserverless.db.collection('users').insertOne( [ { name: 'Zhangsan', age: 18 }, { name: 'Li Si', age: 17 } ] ) ` ### delete data record #### deleteOne ` mpserverless.db.collection('users' ).deleteOne( { name: 'Zhang San' } ) ` #### deleteMany delete users younger than 18 ` mpserverless.db.collection('users').deleteMany ( { age: { $lt: 18 } } ) ` ### Query data records #### findOne ` mpserverless.db.collection('users').findOne( { age: { $gt: 18 } } ) ` #### find Query all user names greater than 18, and return the query results in ascending order of age ` mpserverless.db. coll ection('users').find( { age: { $gt: 18 } }, { projection: { name: 1 }, sort: { age: 1 } } ) ` #### findOneAndDelete Query and delete a piece of data less than and closest to 18 years old ` mpserverless.db.collection('users').findOneAndDelete( { age: { $lt: 18 } }, { sort: { age: - 1 } } ) ` #### findOneAndReplace Query and replace a piece of data whose name is Zhang San ` mpserverless.db.collection('users').findOneAndReplace( { name: " Zhang San" }, { name: "Zhang Sansan", age: 20 }, { upsert: true // if it does not exist, insert it} ) ` #### findOneAndUpdate Query and update the name to Zhang One piece of data for three ` mpserverless.db.collection('users').findOneAndUpdate( { name: "Zhang San" }, { $set: { name: "Zhang Sansan", age: 20 } }, { upsert: true // insert if it doesn't exist} ) ` ### Update data record #### updateOne Update the age of the first Zhang San to 22 ` mpserverless.db.collection('users').updateOne( { name: "Zhang San" }, { $set: { age: 22 } } ) ` #### updateMany Set the age of all Zhang San to 22 ` mpserverless.db.collection('users').updateMany( { name: "Zhang San" }, { $set: { age: 22 } } ) ` #### replaceOne Change the first Zhang San's name to Zhang Asan and age ` 22- ` mpserverless.db.collection('users').replaceOne( { name: "Zhang San" }, { $set: { name: 'Zhang Asan', age: 22 } }, { upsert: true // Insert if it does not exist, and do nothing if it does not exist} ) ` ### Other instructions #### distinct Returns all names whose age field is greater than 18 (if any The same name returns only one) ` mpserverless.db.collection('users').distinct( 'name', { age: { $gt: 18 } ) ` ## ## count Find the number of records in the collection users whose age is greater than 18 ` mpserverless.db.collection('users').count( { age: { $gt: 18 } } ) ` #### aggregate aggregation pipeline query, this pipeline allows users to process data through a series of stage-based operations, please refer to the help document for details https://help.aliyun.com/document\_d etail/435909.html ## Cloud storage mpserverless.file object provides uploadFile and deleteFile methods to manage files. Uploaded files will be network accelerated through CDN. A single file requires less than 100 MB. ### Upload file Alipay applet upload file example ` my.chooseImage({ chooseImage: 1, success: res => { const path = res.apFilePaths[0]; const options = { filePath: path , }; mpserverless.file.uploadFile(options) .then(res => { console.log(res); }) .catch(err => { console.log(err); }); }, }); ` Return example: ` { "fileUrl": "https://mp-…storage/2e7acad6-2212-4863-aaa7-4e89d7d8df4c.png", "filePath": "cloudstorage", "filePath" /2e7acad6-2212-4863-aaa7-4e89d7d8df4c.png" } ` ### Delete the file from the service space according to the file address ` const fileURL = ' https:/ /mp...bspapp.com/xxx-xx/4b82ded0-0118-4de4-9f50-ab13110a1ffb.jpg '; mpserverless.file.deleteFile(fileURL) ` ## Summary EMAS Serverless relies on Alibaba numbers Economic, technical and business capabilities provide serverless services such as cloud functions, cloud storage, and cloud databases. It greatly enhances the value of front-end engineers, allowing developers to quickly implement small program development work, and save time and effort by paying by volume and automatically scaling. In addition, ES also supports static website hosting and cloud invocation modules for the Alipay ecosystem. The linkage between technology and business provides developers with a one-stop mini-program ecosystem service. ## Reference EMAS console: https://emas.console.aliyun.com Help document: https://help.aliyun.com/document\_detail/436030.htmlDevelopment guide: https://help.aliyun. com/document\_detail/444395.html \>> Come and download it for free|E-book "Five Days to Play with EMAS Serverless" << > Copyright Notice: The content of this article is contributed by the registered users of Alibaba Cloud, and the copyright belongs to the original author. Alibaba Cloud Developer Community does not own its copyrights and does not assume corresponding legal responsibilities. For specific rules, please refer to the "Alibaba Cloud Developer Community User Service Agreement" and "Alibaba Cloud Developer Community Intellectual Property Protection Guidelines". If you find any content suspected of plagiarism in this community, fill out the infringement complaint form to report it. Once verified, this community will delete the allegedly infringing content immediately.

阿里云开发者
3.2k 声望6.3k 粉丝

阿里巴巴官方技术号,关于阿里巴巴经济体的技术创新、实战经验、技术人的成长心得均呈现于此。