You won't be serverless in 2022? Look at this nanny tutorial (middle)

Posted by KirstyBurgoine on Sat, 08 Jan 2022 02:20:05 +0100

This article mainly introduces the practice of serverless in applet cloud development

Traditional development mode of applet

Sometimes there is more time for the joint commissioning of front and rear stations. When the project goes online, more operation and maintenance issues need to be considered, such as buying domain names and servers

Cloud development is changing the development mode of applets

What is cloud development

  • Let developers focus more on business development. In the cloud function of cloud development, we can easily obtain some authentication information of applet users openId and unionId, so as to reduce the amount of background development
  • Cloud development is a technical product of a set of comprehensive services. Generally, developing a complete application (small program, Web and mobile application) requires database, storage, CDN, back-end functions, static hosting, user login, etc. However, cloud development integrates these services together and makes the development of an application faster and faster in a new way Convenient, cheap and powerful, leading the new trend of future technology development.

In short, cloud development is a set of technical products of comprehensive services. Generally, developing a complete application (small program, Web and mobile application) requires database, storage, CDN, back-end function, static hosting, user login, etc., but cloud development integrates these services together in a new way, Make the development of an application more rapid, convenient, cheap and powerful, and lead the new trend of future technology development.

We don't need to distinguish between the front-end part and the back-end part. We just need to call the process of where to go like functions. Cloud functions can also be adjusted locally. The adjustment of cloud functions is the same as that of our code

Cloud development advantages

  • Fast online
  • Focus more on our business
  • Independently develop a complete applet. Cloud development provides very rich interfaces. We can easily upload files and other operations through these interfaces
  • There is no need to consider issues such as operation and maintenance. Cloud development is elastic expansion
  • More secure data

What basic capabilities does applet cloud development provide

Applet cloud function billing

Product pricing

Support region

Free Quota

The free quota of each month will be reset at the beginning of each month and will not be accumulated

Quota limit description

Creation and configuration of applet cloud development project

Cloud development project initialization

Find the environment ID of cloud development, click the settings Icon in the cloud development console window, and find the environment name and environment ID in the tab of environment variables.

After opening cloud development, users create a cloud development environment. Wechat applet can have up to two environments. Each environment corresponds to a complete set of independent cloud development resources, including database, cloud storage, cloud function, static hosting, etc. each environment is independent of each other. Each environment has a unique environment ID (the environment name is not unique).


Specify the cloud development environment for developer tools

After the cloud development service is opened, we can see your environment name in the name of the cloudfunctions folder of the applet source code. If the environment name is not displayed in the cloudfunctions folder name, but "unspecified environment", you can right-click the folder, and you can see that the first item in the pop-up window is "current environment", with a small triangle where you can select or switch the established cloud development environment. If the environment is blank, restart the developer tool and choose again.

Specify the cloud development environment for the applet

In the developer tool, open the app in the source code folder miniprogram JS file, find the following code:

wx.cloud.init({
  // env Parameter Description:
  //   The env parameter determines which cloud environment resources will be requested by default for the next cloud development call (wx.cloud.xxx) initiated by the applet
  //   Please fill in the environment ID here. You can open the cloud console to view the environment ID
  //   If it is not filled in, the default environment (the first created environment) will be used
  // env: 'my-env-id',
  traceUser: true,
})

Change your environment ID at env: 'my env ID'. Note that you need to fill in your environment ID instead of the environment name. The results are as follows:

// Because cloud development can create multiple environments, for example, wechat applets can create two free cloud development environments, one for testing and one for official release. If you do not specify an environment on the applet side, the first cloud development environment created for you will be selected by default. We can change the parameters of env to switch the cloud development environment used by the applet.
wx.cloud.init({
  env: 'cloud1-2g12nyjfdh7f4caed9',

  // The global cloud development capability only needs to be initialized once. If the traceUser attribute here is set to true, the user access will be recorded in the user management. The access records can be seen in the operation analysis - user access of the cloud development console.
  traceUser: true,
})

Management of applet cloud development resources

Applet cloud development console

Tencent cloud development web console

We can also use Tencent to develop webpage console to manage cloud development resources. Two points need to be noted. One is login mode, the other is WeChat's official account. Then click on WeChat mobile phone code and choose the small sequence you want to log on on WeChat. The second is to switch to cloud development Cloudbase after entering Tencent cloud background.



Other tools and methods

Cloud development resources also support other ways to call

  • CloudBase CLI: we can use the command line tools provided by cloud development CloudBase CLI Manage the resources in the cloud development environment in batches, such as downloading and updating cloud functions in batches; Batch downloading and uploading of folders in cloud storage;
  • Tencent CloudBase Toolkit: Tencent CloudBase Toolkit is a cloud development plug-in for Visual Studio Code. Using this plug-in can better carry out cloud development project development and code debugging locally, and easily deploy the project to the cloud;

Deploy and upload cloud functions

Cloud function root directory and cloud function directory

There is a small cloud in the cloudfunds folder icon, indicating that this is the root directory of cloud functions. Expand cloudfunctions, and you can see the login, openapi, callback, echo and other folders. These are the cloud functions directory. The miniprogram folder holds the applet's page file

Cloud functions are placed in cloudfunctions, and miniprogram is placed in applet pages, which is not invariable. In other words, you can also modify the names of these folders, depending on the project configuration file project config. The following configuration items in JSON:

"miniprogramRoot":  "miniprogram/",
"cloudfunctionRoot":  "cloudfunctions/",

However, you'd better make the folder of the applet page and the folder of the cloud function in the horizontal relationship and in the root directory of the project for easy management.

Cloud function deployment and upload

  • Right click the cloud function directory, select open in the terminal, and enter the npm install command to download the dependent files;
  • Then right-click the cloud function directory and click "create and deploy: all files"
  • On the cloud development console - cloud functions - cloud functions list, check whether the cloud functions are successfully deployed.

Applet cloud function scenario

Applet cloud development compares application scenarios for obtaining user information in different ways



Applet code

Picture upload


Cloud function routing optimization TCB router

npm i tcb-router



Cloud function timeout

Subscription message

  • Message push location: service notification
  • Message distribution condition: user self subscription
  • Message card: to view the details, you can jump to the applet page

Use steps

1. Get the ID of the message template on the wechat public platform
2. Obtain permission for distribution:

wx.requestSubscribeMessage({
    tmplIds: ['Template ID'],
    success(res) { 
      console.log(res)
    }
  })

Subscribedew: obtain the permission to send messages. Users can choose to subscribe independently

subscribeNew:function(){
   wx.requestSubscribeMessage({
     tmplIds: ['Template ID'],
     success(res) { 
       console.log(res)
     }
   })
}



3. Call the interface to send the subscription message: subscribemessage send

Here is the cloud call subscription message. First, create a cloud function

Need to be in config JSON to configure subscribemessage Send permission

config.json:

"permissions": {
  "openapi": [
    "openapi.subscribeMessage.send"
  ]
}

Cloud function writing

// Cloud function entry file
const cloud = require('wx-server-sdk')

cloud.init()

// Cloud function entry function
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  console.log(event,'sendMessage')
  // Subscription message push
  const res = await cloud.openapi.subscribeMessage.send({
    touser: wxContext.OPENID,
    page: `/pages/index/index`,
    lang: 'zh_CN',
    data: {
      name1: {
        value: event.user_name
      },
      thing7: {
        value: event.name
      },
      phone_number5: {
        value: event.phone
      },
      thing6: {
        value: event.xueli
      }
    },
    templateId: 'yXgBDeiRvjIZ98zOA1212CJeCXw8fj09Ir0sNT3ZXI7H0sw', // Template id
  })
  return res
}

After users subscribe to messages, they can send messages to users.

<view bindtap="sendNew">send message</view>
sendNew:function(){
    wx.cloud.callFunction({
      // Name of cloud function to call
      name: 'sendNew',
      // Parameters passed to the cloud function
      data: {
        openid: '',
        theme:"Tuan Jian",
        address:"xx"
      },
      success: res => {
        console.log(res)
        // output: res.result === 3
      },
      fail: err => {
        console.log(err)
        // handle error
      },
    })
}

Finally, upload and deploy the cloud function and use the mobile phone to test. After success, you will receive the subscription message in the wechat service notification

Timing trigger

The cloud function is executed at a specified time every day


Cloud database

1. Cloud database obtains 100 data breakthroughs

2. Paging query database

3. Fuzzy query


4. Data authority management

5. Three design methods of 1-to-N relationship in cloud database



Applet cloud function debugging

Console debugging


vscode local debugging

Select on the right side of the "cloud functions" list to send trigger events to cloud functions.

I am a programmer Xiaoyue. More dry goods are shared in the company's "front-end advanced journey"

Topics: node.js serverless