头图

First, let's go to the small program we finally developed and developed using the cloud. The code of the small program is as follows:

The applet is named Family Museum, which is mainly used to manage household items. It involves the user account system, item management, classification and search functions, using cloud functions developed by the cloud, database, storage, CMS content management and other capabilities.

1. Get started quickly

If you are not familiar with cloud development, you can first follow the official document to quickly create a small program for cloud development for reference. For the time being, you don’t need to read too much documentation, just run the small program (there are many documents developed in the cloud, and the corresponding document links will be given below for the content involved).

Since the small program we are going to develop involves databases, cloud functions, and cloud storage, we will introduce them in accordance with these parts.

Second, the database

2.1 Content Management System

The handwriting table structure is really a bit slow, and you may make mistakes if you are not careful, so I use the content management system , which can greatly improve work efficiency. For detailed documentation, please move to CloudBase CMS .

Using the above content management system, we can not only manage the content model conveniently (note that the name of the content model should not be changed casually, otherwise there will be problems with the content, so be careful when naming it), and you can also create content.

2.2 Database of Cloud Development Panel

In addition to the above content management system, we can also manage it in the database of the cloud development panel. As shown below:

In addition, the advanced operation also provides some database operation examples, as shown in the following figure:

2.3 Database addition, deletion, modification and query

Here, remember to operate the database in three steps (we will continue in the cloud function for specific example operations):

  1. Which environment database to choose
const DB = wx.cloud.database({
  env: 'test' // 哪个环境
});
  1. Which collection to choose
const users = DB.collection('users');
  1. Add, delete, modify, and check the collection
const user = users.doc('_id');

For more detailed documentation, please refer to: , Modifications and SDK

2.4 Document ID

In the content management system, the document ID is a system field, and currently it can only be automatically generated and cannot be customized. But in some cases, we still want to be able to customize the document ID, such as unified classification of data.

Fortunately, there is another way. The database of the cloud development panel supports customization, so if you really need a custom document ID, you can directly define it in the database of the cloud development panel. However, the field input box of the database custom ID of the cloud development panel has a length limit.

The document ID is very useful when querying a single data record, such as obtaining information about a certain user:

// 以openid 为自定义的文档 ID
// 如果找到则返回该用户信息
// 如果没有找到该用户信息,则表示该用户没有注册。
users.doc('openid').get().then((res) => { console.log(res.data) }).catch((e) => { console.log('未注册')});

Three, cloud function

3.1 Implement the first cloud function

First of all, we are facing my first cloud function document , and realize our first cloud function.

There are mainly one library and two APIs. Note:

Next, we can follow the documentation of the cloud function and have been seeing local debugging.

After reading these, we can officially start cloud function development. The following is an example of obtaining user cloud functions.

3.2 Cloud function combat

  1. We first create a new user cloud function (right-click on the cloud function root directory, in the right-click menu, choose to create a new Node.js cloud function, named user).

  1. Install dependent files

Right-click the user folder, select Open in the built-in terminal, and enter the npm i command to install the dependent files.

  1. Turn on local debugging of cloud functions

After the installation of the dependent files is complete, right-click the user folder and select Open Cloud Function Local Debugging.

The opened cloud function local debugging panel is as follows, pay attention to the check on the right.

  1. Writing cloud functions

The overall code is roughly as follows (the data to be requested can be judged according to the type):

  1. Applet call

First complete the cloud capability initialization in app.js, the code is as follows: (document can refer to: small terminal cloud capability initialization document ).

App({
  onLaunch() {
    if (!wx.cloud) {
      console.error('请使用 2.2.3 或以上的基础库以使用云能力');
    } else {
      wx.cloud.init({
        env: 'cloud1-xxx',
        traceUser: true,
      });
    }
  },
});

Call the cloud function user where needed, the code is as follows:

wx.cloud.callFunction({
  // 云函数名称
  name: 'user',
  // 传给云函数的参数
  data: {
    type: 'get'
  },
})
.then(res => {
  console.log(res.result)
})
.catch(console.error)
  1. Upload and deploy

After debugging and development, you can upload and deploy, as shown in the figure below:

3.3 Cloud function management

All our cloud functions can be managed through the cloud development panel, as shown below:

Four, cloud storage

In fact, in the quick start, there is a cloud development example for uploading pictures in the small program created by default. Copy the example inside, and print out some information before you can use it.

Specific document reference: file storage .

Of course, for the pictures uploaded by users, it is better to have a cropping function. There are many components for cropping pictures in small programs on the Internet. Just find one that suits you.

For the stored content, we can also view it through the cloud development panel, as shown below:

图片

Five, open data

Cloud development also provides a new method to call open data: open data verification and decryption .

Let's take obtaining a phone number as an example, and let's take the actual combat:

  1. Use button component, open-type is getPhoneNumber
<button open-type="getPhoneNumber" bindgetphonenumber="getPhoneNumber"></button>
  1. getPhoneNumber in cloudID

  1. Write cloud function user, call getOpenData API , the main code is:
const { type, cloudID } = event;
// 电话号码授权
if (type === 'getPhone') {
  const res = await cloud.getOpenData({
    list: [cloudID],
  });

  const resPhone = res.list[0].data.phoneNumber;
  return resPhone;
}
  1. The applet terminal calls the cloud function, so that you get the phone number.
wx.cloud.callFunction({
  // 云函数名称
  name: 'user',
  // 传给云函数的参数
  data: {
    type: 'getPhone',
    cloudID, // 这个是上面获取到的 cloudID
  },
})
.then(res => {
  console.log(res.result)
})
.catch(console.error)

Six, summary

In general, the cloud development of small programs has fulfilled our dream of a full stack. It is happy to be a shuttle by one person, but there are actually challenges in the process of exploration. The continuous development and optimization of cloud development requires us to keep pace~

Article source: Tencent IMWEB team

product description

Cloud Development (Tencent CloudBase, TCB) is a cloud-native integrated development environment and tool platform provided by Tencent Cloud. It provides developers with highly available, automatically and elastically scalable back-end cloud services, including serverless capabilities such as computing, storage, and hosting. , Can be used for cloud integration to develop a variety of end applications (small programs, official accounts, web applications, Flutter clients, etc.) to help developers build and manage back-end services and cloud resources in a unified manner, avoiding cumbersome servers in the application development process With construction and operation and maintenance, developers can focus on the realization of business logic, with lower development thresholds and higher efficiency.

Open cloud development: https://console.cloud.tencent.com/tcb?tdl_anchor=techsite
Product documentation: https://cloud.tencent.com/product/tcb?from=12763
Technical document: https://cloudbase.net?from=10004
Technical exchange group, latest information, follow WeChat public account [Tencent Cloud Development CloudBase]


CloudBase云开发
425 声望438 粉丝

云开发(Tencent CloudBase,TCB)是云端一体化的后端云服务 ,采用 serverless 架构,免去了移动应用构建中繁琐的服务器搭建和运维。同时云开发提供的静态托管、命令行工具(CLI)、Flutter SDK 等能力极大的降...