Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

WeChat small program cloud development cloud development capabilities


May 20, 2021 WeChat Mini Program Development Document


Table of contents


Small program cloud development provides several basic capabilities, the following is a description of the main capabilities.

Database

Cloud development provides a JSON database, and as the name implies, each record in the database is a JSON-formatted object. A database can have multiple collections (equivalent to tables in relationship data), which can be seen as an array of JSON, each object in an array is a record in the format of a JSON object.

The conceptual correspondence between the relationship database and the JSON database is as follows:

Relationship type Document type
Database database Database database
Table table Collection collection
Row row Record record / doc
Column Field field

Here's a collection of sample data, assuming we have a books collection that holds a book record with two books:

[
  {
    "_id": "Wzh76lk5_O_dt0vO",
    "title": "The Catcher in the Rye",
    "author": "J. D. Salinger",
    "characters": [
      "Holden Caulfield",
      "Stradlater",
      "Mr. Antolini"
    ],
    "publishInfo": {
      "year": 1951,
      "country": "United States"
    }
  },
  {
    "_id": "Wzia0lk5_O_dt0vR",
    "_openid": "ohl4L0Rnhq7vmmbT_DaNQa4ePaz0",
    "title": "The Lady of the Camellias",
    "author": "Alexandre Dumas fils",
    "characters": [
      "Marguerite Gautier",
      "Armand Duval",
      "Prudence",
      "Count de Varville"
    ],
    "publishInfo": {
      "year": 1848,
      "country": "France"
    }
  }
]

In the book information, we use title, author to record the title and author of the book, characters array to record the main characters in the book, and publicInfo to record the publication of the book. Where we can see that a field can be neither a string nor a number, or an object or array, which is a JSON object.

Each record has an _id field that uniquely flags a record, and a _openid field that flags the creator of the record, the user of the program. I t is important to note that there is no _openid field created on the management side (console and cloud functions), as this is a record created by the administrator. D evelopers can customize _id, but they can't customize and modify _openid. _openid is created by default by the system at the time the document is created by the user of the small program, which developers can use to identify and locate the document.

The database API is divided into two parts: small program ends and server, and the small program end API has strict call permission control, which can directly call the API to perform non-sensitive data in the applet.For data with higher security requirements, you can operate through the server API within the cloud function.The environment of the cloud function is completely isolated from the client, which can be privically secure and safe on the cloud function.

The database API contains the ability to add deletions, using the API operation database only three steps: Get database reference, constructor query / update conditions, and request.The following is an example of a book record of a book in a small program:

// 1. 获取数据库引用
const db = wx.cloud.database()
// 2. 构造查询语句
// collection 方法获取一个集合的引用
// where 方法传入一个对象,数据库返回集合中字段等于指定值的 JSON 文档。API 也支持高级的查询条件(比如大于、小于、in 等),具体见文档查看支持列表
// get 方法会触发网络请求,往数据库取数据
db.collection('books').where({
  publishInfo: {
    country: 'United States'
  }
}).get({
  success: function(res) {
  // 输出 [{ "title": "The Catcher in the Rye", ... }]
  console.log(res)
 }
})

For more database API usage and database management, you can refer to the Database Guidance section.

Store

Cloud development provides a piece of storage space that provides cloud download capabilities for uploading files to the cloud with rights management, and developers can use cloud storage capabilities through APIs in small programs and cloud functions.

The wix.cloud.uploadFile and wx.cloud.downloadFile can be called on the small terminal to upload and download cloud files, respectively. Here are a few simple lines of code to enable users to select a picture within a small program and upload it to cloud management:

// 让用户选择一张图片
wx.chooseImage({
  success: chooseResult => {
    // 将图片上传至云存储空间
    wx.cloud.uploadFile({
      // 指定上传到的云路径
      cloudPath: 'my-photo.png',
      // 指定要上传的文件的小程序临时文件路径
      filePath: chooseResult.tempFilePaths[0],
      // 成功回调
      success: res => {
        console.log('上传成功', res)
      },
    })
  },
})

When the upload is complete, you can see the image you just uploaded in the console.

For more storage APIs and management, you can refer to the Storage Guidelines section.

Cloud function

A cloud function is a piece of code running in the cloud that runs back-end code without the need to manage a server, write within a development tool, and upload a deployment at the click of a button.

An API specifically designed for cloud function calls is available in the small program. Developers can use the getWXContext method provided by wx-server-sdk within the cloud function to get the context of each call (appid, openid, etc.) without maintaining complex authentication mechanisms to obtain a naturally trusted user login state (openid).

For example, let's define a cloud function called add, which adds incoming parameters a and b:

// index.js 是入口文件,云函数被调用时会执行该文件导出的 main 方法
// event 包含了调用端(小程序端)调用该函数时传过来的参数,同时还包含了可以通过 getWXContext 方法获取的用户登录态 `openId` 和小程序 `appId` 信息
const cloud = require('wx-server-sdk')
exports.main = (event, context) => {
  let { userInfo, a, b} = event
  let { OPENID, APPID } = cloud.getWXContext() // 这里获取到的 openId 和 appId 是可信的
  let sum = a + b

  return {
    OPENID,
    APPID,
    sum
  }
}

After uploading the deployment cloud function in the developer tool, we can call it this way in the small program:

In addition to deploying cloud functions for calls, we also support on-premises debugging of cloud functions, which can be tested without deploying cloud functions
wx.cloud.callFunction({
  // 需调用的云函数名
  name: 'add',
  // 传给云函数的参数
  data: {
    a: 12,
    b: 19,
  },
  // 成功回调
  complete: console.log
})
// 当然 promise 方式也是支持的
wx.cloud.callFunction({
  name: 'add',
  data: {
    a: 12,
    b: 19
  }
}).then(console.log)

To operate databases in cloud functions, manage cloud files, call other cloud functions, and more, you can do so using the official npm package wx-server-sdk.

For more cloud function management and APIs, you can refer to the Cloud Function Guidance section.

Cloud calls

Cloud call is the cloud development provides the ability to use small program open interface based on cloud functions, support in the cloud function call service side open interface, such as sending template messages, get small program code and other operations can be done in the cloud function, the details can be seen in the specific development guidelines.

HTTP API

Cloud development resources can also be accessed through the HTTP interface, which is accessed outside the small program, as documented in the HTTP API.

Through this section, we've learned what cloud development is, what capabilities are available, and what we can do, and then follow us into the development guidelines section to see how to get started!