Introduction to Mini Program Cloud Development

Article Directory

Mini Program Cloud Development Official Website

Mini Program Cloud Development w3c tutorial

serverless

Literally understand
serverless = server + less (no server or less server)
The main experience of the evolution and formation of Serverless
1. IaaS (Infrastructure-as-a-Service, providing physical machine services),
2. PaaS (Platform-as-a-Service) , The platform serves both, such as Alibaba Cloud, Qiniu, and even our own nvm, sce, etc.),
3. CaaS (Container-as-a-Service, container-as-a-Service, similar to our current internal docker k8s service),
4. FaaS (Function-as-a-Service, function is both a service, a container is a function, it consumes resources only when it is used, does not contain storage, only contains logic),
5. Baas (Backend-as-a-Service, the backend is both a service) , Provide cloud service functions such as storage, database operations, message forwarding, static services, etc.)

serverless = Faas + Baas

What is cloud development

Why does cloud development appear

Before you want to make a project online, you need a lot of things
https:// need to buy a certificate, some serious certificates (wildcard type*). The application is free, and it is renewed every year.
nginx, apache
python, php, nodejs, asp cdn
(prepaid mechanism), bandwidth, several cores of CPU, and how much memory
all need to be purchased

And the emergence of cloud development--------saving money, time, manpower...

No longer distinguish between front and back ends, but by business. You only need to implement the business logic part, and the tedious configuration of the background is implemented by the cloud for us.

Comparison of traditional background and cloud development of applets

Insert picture description here

Mini Program Cloud Development Features

No need to build a server, cloud call The
open interface of the applet is called without authentication, signature calculation, and access_token in the cloud function, including the ability to call the server and obtain open data (such as WeChat payment, obtaining exercise steps)

Cloud function: The code running in the cloud is authenticated by the WeChat private protocol. Developers only need to write their own business logic code.

Cloud hosting: Support hosting service containers, unlimited frameworks and languages, permanent operation, natural authentication, and fast business migration

Built-in JSON document database
Cloud database: Document database, stable and reliable; supports calling in applets and cloud functions.

Storage: Cloud file storage, comes with CDN acceleration, supports direct upload/download at the front end, and can be managed visually in the cloud development console.

Environment sharing
Environment: An environment corresponds to a set of independent cloud development resources, including resources such as databases, storage space, and cloud functions. (By default, you can have up to two environments, each of which is independent of each other. It is recommended to create one as a test environment and the other as a release formal environment)

Cross-account resource and capability reuse, authorize cloud development resources to be used by other small programs/official accounts.

Mini Program Cloud Development Process

Note: Cloud development of applets requires the use of the registered applet appid. Testing and visitor entry do not have the function of cloud development.

1. Create a project

Change old project to cloud development

Manually add in the project.config.json file

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

Create a new miniprogram and cloudfunctions directory under the project, and move the original content to the miniprogram directory

New project cloud development

Directly choose cloud development to create a project

2. Open resource quota

You can select the resource-balanced free activation first, and then you can jump to the management background page

3. Create an environment

A small program has two free quota environments, one of which can be set as a test environment and the other as a production environment

Management background settings -> environment settings can modify the previous environment

4. Mini terminal project configuration

Configure the cloud function route name in config.js

const config = {
  cloud_route: 'index'
}

export { config }

Cloud function request package utils/cloud-request.js

import { config } from "../config.js"
class CloudRequest{

  constructor(){
    this.cloud_route = config.cloud_route
  }

  request(params){
    wx.cloud.callFunction({
      // 要调用的云函数名称
      name: this.cloud_route,
      // 传递给云函数的参数
      data: {
        // 要调用的路由的路径,传入准确路径或者通配符*
        $url: params.url, 
        data: params.data 
      },
      success: res => {
        params.success(res)
      },
      fail: err => {
        console.log(err)
      }
    })
  }

  /*获得元素上的绑定的值*/
  getDataSet(event, key) {
    return event.currentTarget.dataset[key];
  }
}
export { CloudRequest }

Create a new models folder under the applet directory, specifically to store the logic of requesting cloud function data

import { CloudRequest } from '../utils/cloud-request.js'
class CartModel extends CloudRequest {
    _storageKeyName = 'cart';
    constructor() {
        super()
    };

    /**
     * 获取数据
     * @param {*} callBack 
     */
    getCartData(callBack) {
        callBack(this.getCartDataFromLocal())
    }

    /**
     * 修改数据并返回
     * @param {*} item 
     * @param {*} callBack 
     */
    add(item, counts, callBack) {
        callBack(this._localAdd(item, counts))
    }

    /**
     * 修改数据
     * @param {*} id 
     * @param {*} callBack 
     */
    addCounts(id, callBack) {
        this._changeCounts(id, 1)
        callBack()
    }  
}
export { CartModel }

5. Cloud function terminal project configuration

The operating environment of the cloud function is Node.js, we can use the built-in Nodejs module in the cloud function and use npm to install third-party dependencies

Right-click the current environment and create a new Node.js cloud function

The permissions of cloud functions can be configured

After modification, right click the file to upload and deploy

Use the getWXContext method provided by wx-server-sdk to get the context (appid, openid, etc.) of each call, without the need to maintain a complicated authentication mechanism, to get the natural trusted user login state (openid).

The data in WeChat is stored inside the cloud server, so the relevant data can be obtained directly without authorization and decryption and other related steps

A small example-get WeChat steps

// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init()
// 云函数入口函数
exports.main = async (event, context) => {
	const wxContext = cloud.getWXContext()
	//event接收到的内容即为data传过来的数据
	const {werundata} = event
	console.log(werundata)
	return {
		werundata
	}
}

Applet call

//获取微信运动步数
getWeiRunData:function(){
	wx.getWeRunData({
		success: (result) => {
			console.log(result)
			wx.cloud.callFunction({
				name:"wxrundata",
				data:{
					werundata:wx.cloud.CloudID(result.cloudID)
				},
				success:(res)=>{
					console.log(res)
				}
			})
		}
	})
}

Calling a third-party service to obtain data
On the mini terminal, we can use wx.request to interact with third-party api services. In addition to providing data directly to the mini terminal, can cloud functions obtain data from a third-party server? The answer is yes, and the use of HTTP requests to access third-party services in cloud functions is not restricted by domain names, that is, you do not need to add the domain name to the legal domain name of the request like a small terminal; it is also not restricted by http and https , No domain name but only IP is all right, so cloud functions can be applied in many scenarios, that is, it can easily call third-party services, and it can also serve as the backend of a complete application with complex functions. However, it should be noted that cloud functions are deployed in the cloud, and some terminal communication services such as local area networks can only be performed in small programs.
Routing encapsulation
A user can only create 50 cloud functions in a cloud environment.
We can create multiple routes in one cloud function, which can reduce the number of cloud functions.
tcb-router is a small program based on koa style · cloud development cloud function light Weight class routing library, mainly used to optimize server-side function processing logic

installation

npm install --save tcb-router
// 云函数入口文件
const cloud = require('wx-server-sdk')
const TcbRouter = require('tcb-router');

const returnUtil = require('utils/ReturnUtil.js')
const banner = require('service/bannerService.js')
cloud.init()


// 云函数入口函数
exports.main = async (event, context) => {
  const app = new TcbRouter({ event });
  // app.use 表示该中间件会适用于所有的路由
  app.use(async (ctx, next) => {
    ctx.data = {};
    await next(); // 执行下一中间件
  });

  // 获取轮播
  app.router('getBanner', async (ctx, next) => {
    ctx.data = await _bannerItem(banner.getBanner())
    ctx.body = await returnUtil.success(ctx)
    await next();
  })

  return app.serve();
}

Public return value package utils/ReturnUtil.js

  /**
   * 成功调用
   * @param {*} ctx
   * @retuen 
   */
  const success = ctx => {
    return {
      code: 0,
      message: 'success',
      data: ctx.data
    }
  }

  /**
   * 调用失败 
   * @param {*} ctx
   * @param {*} msg
   * @retuen 
   */
  const error = (ctx,msg) => {
    return {
      code: 400,
      message: msg,
      data: ctx.data
    }
  }

  module.exports={
    success,
    error
  }

Some instructions when using tcb-router:

Under normal circumstances, we do not recommend that you use a cloud function to call other cloud functions. This approach will cause the execution time of the cloud function to increase a lot, and it will also consume the resources of the cloud function. We can use tcb-router To handle situations that require cross-cloud function calls;
it is worth noting that tcb-router will carry all cloud functions in one cloud function, and it is recommended not to use tcb-router for cloud functions that have higher requirements for concurrency. One inside. The upper limit of the number of concurrency of each cloud function is 1000, which can handle 100,000 requests per second, but if a large number of different cloud functions are integrated into one, especially some cloud functions that take a long time will be seriously delayed. Performance declines, and these cloud functions will share these 1000 concurrency, so be careful to choose according to the situation; the
cloud function will have a cold start time (for example, no one calls this cloud function for more than ten minutes, when the cloud function is called for the first time It will be slower), when we use tcb-router to integrate multiple cloud functions with similar functions and not particularly high concurrency (less than a few thousand per second) into a cloud function, so as to reduce the possibility of cold start ;

6. Database operations

Cloud storage database creation and connection establishment
Database design (primary key, field, data type, meaning)

Create collections, import data

Local data format: json file, there is no need to add a comma between each group of data

{"_id":"9afd9b6a5d2182550289a5a349bffa78","show":true,"name":"test10","age":12.0,"sex":0.0}
{"_id":"f896855d5cfb5f6901c18d424a19b0bd","show":true,"name":"test02","age":20.0,"sex":1.0}

Database operation package

// 公共BaseModel
const cloud = require('wx-server-sdk');
// 环境
cloud.init({ env: process.env.Env })
const db = cloud.database();

/**
 * 查询处理 
 * @param  {object} model       集合名称
 * @param  {String} id          查询id
 * @return  {object|null}       查找结果
 */
const findById = (model, fields = {} , id ) => {
  try {
    return db.collection(model)
      .doc(id)
      .field(fields) 
      .get()
  } catch (e) {
    console.error(e)
  }
}


/**
 * 查询处理 带多条件的
 * @param  {object} model         集合名称
 * @param  {Object} [options={}]    查询条件
 * @param  {Number} [page]        开始记录数
 * @param  {Number} [size]        每页显示的记录数
 * @return  {object|null}         查找结果
 */
const query = (model, fields = {}, options = {}, page = 0, size = 10, order = { name: '_id', orderBy:'asc'} ) => {
  try {
    return db.collection(model)
    .where(options)
    .field(fields) 
    .skip(page)
    .limit(size)
    .orderBy(order.name, order.orderBy)
    .get()

  } catch (e) {
    console.error(e)
  }
}

/**
 * 新增处理
 * @param  {object} model  集合名称
 * @param  {object} params 参数
 * @return {object| null}  操作结果
 */
const add = (model, params) => {
  try {
    return db.collection(model).add({
      data: params
    });
  } catch (e) {
    console.error(e);
  }
}

/**
 * 编辑处理
 * @param  {object} model      集合名称
 * @param  {object} params     参数
 * @return {object|null}       操作结果
 */
const update = (model, params) => {
  // let id = params._id
  // delete params._id
  try {
    return db.collection(model).doc(params._id)
    .update({
      data: params
    })

  } catch (e) {
    console.error(e);
  }
}

/**
 * 删除结果
 * @param  {object} model      集合名称
 * @param  {String} id         参数
 * @return {object|null}       操作结果
 */
const remove = (model, id) => {
  try {
    return  db.collection(model).doc(id).remove()
  } catch (e) {
    console.error(e)
  }
}

module.exports = {
  query,
  findById,
  add,
  update,
  remove
}

Operate an external database.
If your project already uses MySQL, it is not convenient to migrate the database to a cloud development database or your business prefers to use MySQL. In this case, you can also connect to a self-built MySQL database and transfer the data to it. It is rendered on the small terminal.

The MySQL built by the server or the relational database service purchased from cloud service companies such as Tencent Cloud can be connected using the cloud function when the external network connection and IP whitelist are opened, which means that the cloud function is deployed In the public network, you can only access the database resources of the public network (intranet or local databases are not acceptable). If your database can be accessed from the public network, you need to open the external network connection and IP whitelist. However, the cloud function currently does not have a fixed IP, so the IP whitelist list that needs to be added to the database will be relatively long.

If you don't want to expose the database to the public network environment, but can be accessed by cloud functions, here is recommended to use Tencent Cloud's private network. Tencent Cloud products on a private network (such as cloud functions developed by the cloud and MySQL database of Tencent Cloud) can be interconnected through a peer-to-peer connection provided by Tencent Cloud.

Private network service creation and operation of mysql database

7. Data storage

Image resources are uploaded and stored, and can be directly dragged and uploaded

8. Local debugging

Click on the cloud function in the management background to open the cloud function list for local breakpoint debugging, and you need to install dependencies

note:

If the local debugging has been turned on, the modified cloud function cannot take effect directly, you need to upload and deploy and then restart the local debugging

9. Alarm rule setting (customized, with cloud functions as the object)
10. Gray release
Click the version and configuration behind the function whose version needs to be set, and you can see the version of this function. Note that latest is the current latest version If the version has not been set, it is also the version of the cloud function currently accepting the request.
Click Create New Version to create a new version for the current latest version. After publishing, the latest snapshot version can be created successfully.
The new created at this time The version can’t be accessed by the front-end. You need to click to assign traffic ratio. Set the access ratio. The
default ratio is latest accounted for 100%. Select the version just created in the drop-down box and set the ratio to 100% to allow users to access at this time. The version just created. As long as the ratio is set, the purpose of grayscale release can be achieved

11. Operation and maintenance monitoring (database, storage, cloud function, SMS, etc.)

Cloud function catalog description

|–CloudFunction

|----config (related parameter configuration, sensitive information)

|----fields (specify data fields returned in the database)

|----models (operating database package, adding, deleting, modifying and checking)

|----service (Get the corresponding data from the database)

|----action (interface data assembly return)

|----test (interface service test)

|----utils (public method encapsulation)

|----index.js (routing preparation)

Common problems and solutions