Quick Start with WeChat Mini Program Cloud Development (4/4)

Preface

In the previous chapter " Quick Start to Cloud Development of WeChat Mini Programs (3/4) "
, we learned about cloud storage and cloud database in the previous sharing. Next, let's learn about cloud functions.

Cloud function

Cloud function is equivalent to the concept of server interface, and it does not belong to the applet code. It runs backend code in the form of functions to respond to events and call other services. The running environment is Node.js.

Since I see that everyone’s project directory structure is not unified, I will unify the project directory structure first.
It is divided into three parts:

  1. cloudfuntions folder cloud functions root directory
  2. The miniprogram folder contains the page files of the mini program.
  3. project.config.json configuration file
    Configure in project.config.json:
{    
  "miniprogramRoot":  "miniprogram/",
  "cloudfunctionRoot": "cloudfunctions/",
  // ... 
}

After agreeing on the directory structure, let’s first experience the charm of cloud functions

Create a new cloud function


Create a new sum cloud function.

When creating a new cloud function, the cloud function will be automatically deployed to the cloud function list in the cloud development control panel.

Then we will implement this sum cloud function.

// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()

// 云函数入口函数
exports.main = async (event, context) => {
  const sum = event.a + event.b
  return sum
}

Two parameters, a and b, are passed in through the mini program, and then the cloud function sums the two parameters and returns them to the mini program. After writing, right-click to upload.

After the upload is successful, the mini program development tool will prompt you, and the cloud function list update time will also change in the cloud development control background.

Call cloud function

Call cloud functions through callFunction

wx.cloud.callFunction({
        // 要调用的云函数名称
        name: 'sum',
        // 传递给云函数的event参数
        data: {
          a: 1,
          b: 2,
        }
      }).then(res => {
        console.log(res.result)
        // output: res.result === 3
      }).catch(err => {
        // handle error
      })

Cloud function debugging

Uploading cloud functions requires waiting time, and usually in actual development, the cloud function you are currently writing may require multiple steps to be triggered. At this time, it is best to test whether the cloud function is correct locally, and then deploy and upload it to cloud. So how to test it locally? Right-click the cloud function directory that needs to be tested and select local debugging.

You will first be prompted to initialize the node-related environment

. After the installation is completed, you can see the cloud function interface.

You can choose manual triggering or simulator triggering according to the situation. We choose manual triggering.

After selecting manual trigger, enter the test parameters and click Call

{
  "a": 1,
  "b": 2
}

After the call is successful, it will be displayed:

In addition, you can also perform online cloud function testing in the cloud development control panel.

Since there is a network request process when using cloud testing, you need to wait for a while.

Cloud function log

Each cloud function call record can be found in the cloud function log, and the console.log printed in the cloud function can be viewed.

// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()

// 云函数入口函数
exports.main = async (event, context) => {
  const sum = event.a + event.b
  console.log("sum",sum)
  return sum
}


Supports more precise positioning and search of logs through function name or Request ID, request status, and time interval. When debugging cloud functions, you cannot only rely on the error returned by the return of the mini program, because it only feeds back the calling results of the cloud function and whether an error occurs during the call. More importantly, you still need to use console.log in the cloud function to print the cloud function. Some log situations during execution.

Operation database

In the past, the database was directly operated by the small program, and cloud functions can also be operated. Next, let’s take a look at how to write and operate the database using cloud functions. Create a new cloud function and name it memo.

First, we write the route first and call different methods through different action parameters passed in.

// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
    
  if (event.action && memoHelper[event.action]) {
    const result = await memoHelper[event.action](wxContext, event)
    return result
  }

  return {
    message: 'This action was not found',
    error: -1,
  }
}
//数据库
const db = cloud.database()
const memoHelper = {
  //查询所有记录
  async quearyAllMemo(context, params) {
    let res = await db.collection('memos').orderBy('updateTime', 'desc').where({
      openid: context.OPENID
    }).get()
    return res
  },
  //添加记录
  async addMemo(context, params) {
    params.data.openid = context.OPENID
    let res = await db.collection('memos').add({
      data: params.data
    })
    return res
  },
  //删除
  async deleteMemo(context, params) {
    console.log("deletememo", params)
    let res = await db.collection('memos').doc(params._id).remove()
    return res
  },
  //修改
  async updateMemo(context, params) {
    params.data.updateTime = new Date()
    let res = await db.collection('memos').doc(params._id).update({
      data: params.data
    })
    return res
  },
}

However, it should be noted here that adding data on the mini program will automatically add the openid of the current operator, while cloud functions will not. However, in order to identify the source user of this data, you need to add it manually.

To obtain openid, you need to obtain the WeChat calling context in the cloud function through getWXContext. In addition, you can also obtain the following parameters:

Call the cloud function to operate the database, taking adding as an example:

wx.cloud.callFunction({
      name: 'memo',
      data: {
        action: 'addMemo',
        data: params
      }
    });

So at this time, you will definitely have a question in your mind. Since both can be called, what is the difference between the two ends?

The difference between the two ends

Cloud development includes SDKs that run on the mini program side and SDKs that run on the cloud function side. They can both add, delete, modify, and check cloud databases, upload, download, and delete files to cloud storage, and they can also call cloud functions, and Make a request to a third-party API. For a simple project, we only need to use the SDK of the mini program, such as our memo mini program.

Although there are many similarities between the mini program SDK and the cloud function SDK, there are many differences. The specific manifestations are as follows:

Permission system

The mini program comes with WeChat user authentication and security rules. Users can log in to the mini program without authentication. Operations on databases and cloud storage are controlled by simple permissions or security rules. For example, when permissions are set to only the creator can read and write. , user A cannot see or modify the data created by user B, ensuring the security of the mini-program SDK when operating resources such as cloud storage, cloud databases, and cloud functions; while the cloud function SDK has the highest authority over cloud development resources (Administrator permissions), it is not affected by simple permissions or security rules. When user A calls the cloud function, he can also add, delete, modify and check the data created by user B (can be restricted by the logic of the cloud function).

It is worth mentioning that only the mini-program SDK calls cloud functions to obtain the user's login status. The management side (console, cloud functions) cannot obtain the user's openid by calling cloud functions (if necessary, you can use a database, etc. The method is to pass in openid as a parameter).

Database operations

Directly using the SDK to add, delete, modify, and query the database on the applet. Compared with first calling the cloud function and then operating the database through the cloud function, the former is both faster (directly CRUDing the database is about 100ms faster) and faster. The resource consumption of cloud functions (the latter will consume GBs of resource usage and external network outgoing traffic of cloud functions) is better. Under normal circumstances, it is more recommended to use this solution.

However, operating the database through cloud functions is safer than directly operating the database through the mini program (the code on the mini program is easy to be reversed), and the processing is more flexible (for example, all modifications to the mini program need to be published and approved, while the cloud function is more secure). The function end will not), and thirdly, it is easier to cross-end (multiple small programs can share a set of cloud function codes in a cloud development environment).

Generally speaking, if it can be processed with the mini program SDK, try to use the mini program SDK. Putting data processing on the mini program can effectively reduce the pressure on cloud functions, increase processing speed, and reduce usage costs.

API support

For example, the real-time data push watch method only supports the mini-program SDK, and the joint table query lookup in the aggregation query can only be performed on the cloud function side; if the database uses simple permission control, the mini-program cannot batch update the database. Or delete (where.update, where.remove). In terms of query data, the mini program can query up to 20 items, and the cloud function can support up to 1,000 queries.

network request

The network request initiated using wx.request() on the mini program only supports https, http and ip are not supported, and the domain name needs to be registered. On the cloud function side, we can use third-party modules such as axios and got to initiate network requests. Not only does it support https, http, ip, etc., but the domain name does not require registration. In addition, cloud functions can also have fixed IPs, especially when databases, public account development, etc. have certain requirements for IP whitelists.

Cloud call

Cloud calling is the ability provided by cloud development to use small programs and Tencent Cloud open interfaces based on cloud functions, such as message subscription, cloud payment, image processing, etc. Although cloud calling also has https calls, cloud functions are more secure and convenient.

timed trigger

The call to the mini program SDK can only be executed when the user opens and uses the mini program, while cloud functions can be separated from the mini program and execute some tasks regularly/regularly under the action of timing triggers.

Backend services

Cloud Function can not only use the Cloud Function SDK to call resources in the cloud development environment with the support of the wx-server-sdk module, but can also install some Node.js modules to provide some back-end services for small programs, such as sending and receiving emails. , text messages, notification messages, image, audio and video processing, etc.

Summarize

All the basic common operations of Cloud Development Quick Start are over in this chapter. Everyone must learn to continuously optimize. Optimization is a continuous process. We must use the knowledge we have learned to continuously do local optimization instead of focusing on the entire project. structure.

To learn more about the quick introduction to cloud development of WeChat mini programs, please pay attention to CRMEB

Guess you like

Origin blog.csdn.net/CRMEB/article/details/132171760