UniCloud is a cloud development platform based on Serverless mode and JS programming provided by DCloud, Alibaba Cloud and Tencent Cloud for developers.

UniCloud web console address: unicloud.dcloud.net.cn

UniCloud official documentation: github.com/dcloudio/un…

Supported from HBuilderX 2.5.8 onwards.

UniCloud instructions

The value of uniCloud

  • For front-end programmers, from now on you get a new skill, with familiar JS, easy to deal with the whole business front and back.
  • For developers:
    • Development costs have plummeted. No more hiring PHP or Java server engineers, saving at least a few hundred thousand a year;
    • You only need to focus on your business. You don’t need to worry about server operation and maintenance, flexible capacity expansion and anti-ddos attacks.
    • If you do not release H5, you will not need to purchase a registered domain name. Applets and apps can use servers without domain names;
    • For agile businesses, the communication costs of separating the front and back ends are really unnecessary. Consider dividing responsibilities by business rather than by front and back office.

How uniCloud works

Develop and run processes

  • Developers create uniCloud cloud environment for the project in HBuilderX (you can choose Ali Cloud or Tencent Cloud), write JS code in the cloud function directory, upload and deploy the cloud function to Ali Cloud or Tencent Cloud serverless environment.
  • Front-end code passesuniCloud.callFunction()Method calls the cloud function.
  • Cloud functions can perform JS operations, read and write cloud database (NoSQL), read and write storage and CDN, operate the network, and return data to the front end

Development process, connection to DCloud server; The running process is that the mobile terminal is directly connected to ali Cloud or Tencent Cloud Serverless environment, without transfer through DCloud server.

The underlying environment of uniCloud is the same as the infrastructure environment of wechat and Alipay mini program cloud development. Sufficient guarantee of function, performance and stability. Tencent Cloud provides basic serverless capabilities, based on which the wechat team encapsulates wechat cloud development, while the DCloud team encapsulates uniCloud.

Small program cloud development has become a trend, wechat small program, Alipay small program, Baidu small program all provide cloud development. Wechat announced that more than 500,000 developers have used cloud development, wechat’s own life payment, ride code and other big live applications are using cloud development. However, the popular technology has been unable to cross over, and they only support their own small programs. UniCloud solves the cross-end problem, making cloud development available to all applications on uni-App.

UniCloud infrastructure includes the following three parts:

  • Cloud functions: JS code that runs in the cloud. Runs in a customized Node environment with good performance and powerful functionality. Serverless environment does not need to purchase servers to process and increase capacity. Cloud functions are paid according to quantity. No matter how large the concurrency is, it can withstand it (Ali Cloud Serverless has passed the test of Double 11).
  • Database: A NOSQL-based JSON database that can be read and written in cloud functions. This kind of database is more natural for the front-end engineer, without the need to learn SQL, understand relationships, and design primary keys.
  • Storage and CDN: Storage and CDN can be manipulated either in the front end or in cloud functions. inuniCloudWith the security mechanism provided, direct CDN can be applied from the front end to avoid server transfer time and bandwidth occupation, and no stolen transmission occurs.

UniCloud to fit

Create the uniCloud project

  • inHBuilderX 2.5.8 +Create a new project, select uni-app project and check itEnable uniCloud
  • Select the service provider on the right

  • For older Uni-app projects, you can also right-click on the project and choose “Create uniCloud Cloud Development Environment” from the menu
  • In the template for the new Uni-app project, there is oneHello uniCloudProject template that demonstrates the use of various cloud functions.

After the uniCloud cloud development environment is created successfully, the project has a special directory named CloudFunctions with cloud ICONS.

Create and bind service Spaces

After the project environment is established, a service space needs to be selected for the project. If a developer’s account does not have real name authentication, he/she will first need to have real name authentication (this is a legal requirement, and also a requirement of cloud service providers such as Ali Cloud and Tencent Cloud).

A developer can have multiple service Spaces, each of which is an independent Serverless cloud environment. Cloud functions, databases, and storage are isolated between different service Spaces.

Service space and mobile project are many-to-many bindings. Under the same account, a project can be associated with multiple service Spaces. A service space can also be accessed by multiple projects.

  • In the cloud function directorycloudfunctionsRight-click the menu to create a service space, which opens the Web consoleunicloud.dcloud.net.cnTo create a

  • After the service space is created, the directorycloudfunctionsRight click and click in the menuSelect the cloud service spaceBind the service space you created earlier.

instructions

  • If no real-name authentication is performed, the system switches to the real-name authentication page and opens the service space after the verification
  • It may take several minutes to create the service space. Check whether the service space is created on the console
  • An application can set collaborators in dev.dcloud.net.cn (choose Application > Set project members) to realize the common use of a cloud service space by multiple people. (Requires HBuilderX 2.5.9+)
  • If a project corresponds to only one service space, the front-end can use this service space directly. If a project binding the multiple services space, you need to do first initialized, specific reference: uniapp. Dcloud. IO/uniCloud/in…

Creating a cloud function

uniCloudAfter a project is created and bound to a service space, developers can use thecloudfunctionsRight-click directory to create cloud function.

After the cloud function is created, a special directory is generated using the name of the cloud function. The directory automatically generates index.js, which is the entry file of the cloud function and cannot be renamed. If the cloud function needs to import other JS, it can be referenced in the index.js entry file.

Pay attention to

  • When different projects use the same service space, the same cloud function cannot be used. You can manually delete the cloud function with the same name in the Web console of uniCloud to release the function name.
  • If the new cloud function has the same name as an existing cloud function on the server, it will be overwritten by the new function. Be sure to pay attention. This issue will be fixed later.
  • Limit the size of a single cloud function to 10M (including node_modules)

Writing cloud functions

The syntax of cloud functions is supplemented by uniCloud’s proprietary API on top of ordinary Node.js. You can refer to the API development documentation or directly select the Hello uniCloud template to experience when creating a project.

HBuilderX provides good syntax tips and go to definition support for uniCloud development, and for apis in code, select and press F1 to view the corresponding documentation directly.

The following is an example of a cloud function

'use strict';
const db = uniCloud.database()
exports.main = async (event, context) => {
    // Event indicates the parameters uploaded by the client
    const collection = db.collection('unicloud-test') // Get the collection object of the table 'unicloud-test'
    const res = await collection.limit(10).get() // Get 10 entries in the table in JSON format
    return res // Return json to the client
};
Copy the code

Run and debug cloud functions

After compiling the cloud function, right-click the directory of the cloud function in the project manager, and choose “Upload deployment cloud function” and “Upload and run test cloud function” from the pop-up menu. As shown below:

The former is only deployed, while the latter runs concurrently after deployment and generates logs.

In the Cloud function editor, press Ctrl+ R to run the shortcut key, or click the Toolbar to run, and you will see the shortcut instructions for uploading and running the cloud function directly. Ctrl+ R and press Enter or select 0 to efficiently see the run results and log output on the console.

Cloud functions currently cannot break debug and can only print console.log to view logs.

Call the cloud function on the mobile phone

In the uni-app front-end code, the cloud function is called through the unicloud.callfunction method. See the callFunction documentation for details

In the following code, the cloud function named test is called and the JSON data of Data is sent as the uplink parameter.

/ / promise
uniCloud.callFunction({
    name: 'test'.data: { a: 1 }
  })
  .then(res= > {});
/ / callback methods
uniCloud.callFunction({
    name: 'test'.data: { a: 1 },
    success(){},
    fail(){},
    complete(){}});Copy the code

Viewing logs on mobile phone

Uni-app runs on all terminals, and you can view logs on the mobile terminal. As an added bonus, the console in HBuilderX will also print console.log output from the cloud function in real App mode.

The real machine debugging on the App side outputs the cloud function log, as shown in the following figure

The code of the cloud function executed

'use strict';
exports.main = async (event, context) => {
    console.log('-- -- -- -- -- -- -- -- -- -- -- --');
    console.log('Cloud function log Output');
    console.log('-- -- -- -- -- -- -- -- -- -- -- --');
    return {
        action: 'log demo'}};Copy the code

Log output

  • When running to H5, you need to view the logs in the browser console, but only the front-end logs, not the console.log inside the cloud function.
  • To run the applet, you need to view the logs in the console of the applet development tool, but only the front-end logs, not the console.log inside the cloud function.

The uniCloud Web console does not currently have the ability to view run logs, this will be provided later.

UniCloud is used in the applet

Each small program platform requires the network server domain name of small program application to be configured in the background of small program management, otherwise the network cannot be connected.

After using uniCloud, developers will no longer need to purchase and record the domain name themselves, but directly fill in the uniCloud domain name in the mini program management background.

Set the request domain name and uploadFile domain name on the applet management background based on the following table. The domain names in the following table are all owned domain names of Ali Cloud or Tencent Cloud, not the domain names of DCloud.

Service provider Request Valid domain name UploadFile Specifies the valid domain name
Ali cloud api.bspapp.com bsppub.oss-cn-shanghai.aliyuncs.com

Small program development tool real machine preview function, you must add the domain name whitelist, otherwise can not call the cloud function. The PC preview and real machine debugging of the simulator are not affected.

UniCloud is used in H5

H5 front-end JS access cloud functions, which involves cross-domain problems. As a result, front-end JS cannot connect to the cloud function server. The processing method is as follows:.

  • When running on the H5 side, you can ignore cross-domain issues using the built-in HBuilderX browser (2.5.10+ for MAC).
  • When issuing the IP address to H5, you need to perform operations in the uniCloud background and bind the secure domain name. Otherwise, the IP address cannot be accessed due to cross-domain problems. (in thecloudfunctionsRight-click the directory to open uniCloud background)

UniCloud Background configuration security domain name:

  • If you want to use an external browser when running, the solution is as follows:
    • Method 1: On the uniCloud Web console, bind the address of the test period to the security domain name, for example, localhost:8080 and 192.168.0.1:8080
    • Method 2: install cross domain in an external browser plug-ins, see: ask.dcloud.net.cn/article/352…

H5 front-end page deployment is faulty

Ali Cloud Serverless currently does not support the deployment of H5 front-end pages. Developers need to prepare web servers by themselves, click the release menu in HBuilderX, generate H5, and deploy the generated front-end files under Nginx and other Web servers.

Then register or use the existing domain name, handle the resolution of the domain name in the domain name service provider, pointing to your Nginx server IP.

Finally, the domain name is configured as a secure domain name through the uniCloud background, which can be accessed in the browser.

M3w.cn Secondary domain name application

If you need to go online H5 in order to fight COVID-19 and have no time to register a domain name, you can apply for the secondary domain name of M3w.cn provided by DCloud, for example: Hellounicloud.m3w.cn. At this time, please use your registered DCloud account email application to [email protected], providing your APPID, secondary domain name you plan to use, resolved IP address, application purpose.

If you do not release H5, you do not need to apply for or prepare a domain name yourself to use uniCloud. App and small programs directly call the cloud function.

Initialize the project database

Since HBuilderX 2.5.11 uniCloud provides db_init.json for quick database initialization.

Directions for use

  • incloudfucntionsDirectory can be created by right clickingdb_init.json.
  • indb_init.jsonRight-click to initialize the database.
{
    "collection_test": { // set (table name)
        "data": [ / / data
           {
                "_id": "da51bd8c5e37ac14099ea43a2505a1a5"."name": "tom"}]."index": [{ / / index
            "IndexName": "index_a".// Index name
            "MgoKeySchema": { // Index rules
                "MgoIndexKeys": [{
                    "Name": "index".// Index field
                    "Direction": "1" // Index direction, 1: ASC- ascending, -1: desC-descending}]."MgoIsUnique": false // Whether the index is unique}}}}]Copy the code

UniCloud Basic concept

Service space

A service space corresponds to a set of independent cloud development resources, including databases, storage space, and cloud functions. Service Spaces are isolated from each other.

Each service space has a globally unique space ID. In the future, an application will be able to connect to multiple service Spaces at the same time, and you will need to declare a space ID in your code to tell your code which cloud service space to connect to.

Developers can create new service Spaces in HBuilderX as follows:

Or create a service space on uniCloud’s Web console unicloud.dcloud.net.cn.

Developers need to bind the service space for their projects before they can upload cloud functions and operate databases and storage resources in the service space.

The database

UniCloud provides a JSON-formatted document database, where each record is a JSON-formatted object. A database can have multiple collections (equivalent to tables in relational data), which can be viewed as a JSON array where each object in the array is a record in the form of a JSON object.

The conceptual mapping between relational database and JSON document database is shown in the following table:

relational JSON document type
Database database Database database
Table table A collection of the collection
Row, row Record/doc
Column column Field in the field,

More cloud database introduction reference specifications.

Cloud function

Cloud functions are functions that run in the cloud (server side).

Developers do not need to buy or build a server, but only need to write function code and deploy it to the cloud to call it on the client (App/H5/ small program, etc.). At the same time, cloud functions can also call each other.

A cloud function is written just like a locally defined JavaScript method, and the code runs in the cloud node.js. When a cloud function is called by a client, the defined code is executed in the Node.js runtime environment.

Developers can perform network requests and other operations in cloud functions just like using JavaScript in node. js environment, and can also use a variety of services through cloud function server SDK, such as database and storage API provided in cloud function SDK for database and storage operations. Refer to the database and storage backend API documentation for this section.

Developers are available in HBuiderX, incloudfunctionsRight-click on the directory and create a new cloud function as follows:

After modifying a cloud function, upload the modification to the cloud system for it to take effect.

More cloud function introduction reference specification.