Li Chengxi is a senior engineer at Tencent Cloud. After graduation in 2014, I joined Tencent AlloyTeam and successively took charge of projects such as QQ group, Fancy live broadcast and Tencent documents. In 2018, he joined Tencent Yunyun Development team. Focus on performance optimization, engineering and small program services. Weibo | zhihu | dead simple
The original link
What is applets · cloud development
Small program · Cloud development is a set of basic capabilities of small programs jointly developed by wechat team and Tencent Cloud team. In short, cloud capabilities will become the basic capabilities of small programs. The whole set of functions is based on a complete set of small program background development programs developed by Tencent Cloud Base, which is newly launched by Tencent Cloud.
· Cloud development provides developers with a complete cloud process and simplifies back-end development and operation and maintenance concepts. Without setting up servers, core business development can be realized quickly by using API provided by the platform.
The solution currently supports three basic capabilities:
-
Storage: upload/download cloud files directly in front of the small program, and manage them visually in the small program cloud console
-
Database: A document database that can be operated on the front end of an applets or read and write in cloud functions
-
Cloud function: the code running in the cloud, wechat private protocol natural authentication, developers only need to write business logic code
In the future, we will integrate more service capabilities to provide stronger cloud support for small programs.
How to use applets · Cloud development
In the small program side, directly use the interface provided by the official, in the cloud function side, directly use the Node SDK provided by the official, you can operate your cloud resources. Before the development of small procedures to worry about the database construction, file system deployment, all without.
You only need to have the small program development IDE in the cloud development, open, fill in the environment ID, you can have the small program cloud capability!
Of course, in fact, cloud development does not exclude the original background architecture, through the following architecture, you can also seamlessly compatible with the original background services, but also simplify some small program authentication logic:
Next, I’ll show you how to use these cloud resources on the small application side and on the server side.
Using cloud capabilities
The small program end
Client, in this case, in the applet side. To use cloud development capabilities, do the following:
- in
app.json / game.json
Add fields in"cloud": true
- Json field cloudfunctionRoot is added to specify the directory to store cloud functions
- Initializing cloud development capabilities:
//app.js
App({
onLaunch: function () {
wx.cloud.init({
traceUser: true // The user information is displayed in the user panel of the Cloud Development Console}); }});Copy the code
Applets – side initialization capability document
In user management, the access user list of the applet that uses cloud capabilities is displayed. By default, the access time is arranged in reverse order. The access time is triggered when the wx.cloud.init method is called on the applet side, and the traceUser parameter is passed to true.
The service side
If you want to work with files, databases, and cloud resources in the cloud, you can use our server SDK to do so. First, go to one of your cloud functions and install the following dependencies:
npm i --save tcb-admin-node
Copy the code
Class in the cloud function
// Initialize the example
const app = require('tcb-admin-node');
// Initialize the resource
SecretId and secretKey are not required under cloud functions.
// env If not specified, the default environment will be used
app.init({
secretId: 'xxxxx'.secretKey: 'xxxx'.env: 'xxx'
});
// Use the default environment for cloud functions
app.init()
// Specify the environment under the cloud function
app.init({
env: 'xxx'
});
Copy the code
The server initializes the document
storage
Cloud development provides storage space, file upload, file download, CDN accelerated file access and other capabilities, developers can use these capabilities on the small program side and server side through API.
The small program end
// Select the image
wx.chooseImage({
success: dRes= > {
// Upload the image
const uploadTask = wx.cloud.uploadFile({
cloudPath: `The ${Date.now()}-The ${Math.floor(Math.random(0.1) * 10000000)}.png`.// Random image name
filePath: dRes.tempFilePaths[0].// Local image path
success: console.log,
fail: console.error
});
},
fail: console.error,
});
Copy the code
The applets store documents
The service side
const app = require('tcb-admin-node');
app.init();
app.uploadFile({
cloudPath: "cover.png".fileContent: fs.createReadStream(`${__dirname}/cover.png`)
}).then((res) = > {
console.log(res);
}).catch((err) = > {
console.error(err);
});;
Copy the code
The console
The uploaded file will appear in the console, as shown below. You can delete, download, or view the details of an image in the console.
You can also control the overall file permissions, here are some details.
The server stores documents
The database
Applets cloud provides document-oriented database, database contains multiple collections (equivalent to tables in relational data), collection is approximately a JSON array, each object in the array is a record, the record format is JSON document.
Each record has an _ID field that uniquely identifies the record, and an _openID field that identifies the record’s creator, the user of the applet. Developers can customize the _id, but not on the applet side (on the server side) _openID. _openID is created by default by the system at document creation time, based on applets users, and can be used by developers to identify and locate documents.
Database API is divided into two parts, the small program side API and the server side, the small program side API has strict call permission control, developers can directly call API in the small program for non-sensitive data operations. For data with higher security requirements, the cloud functions can be operated through the server API. The cloud environment is completely isolated from the client, and the database can be operated privately and securely on the cloud.
The database API contains the ability to add, delete, change, and query. Using the API to manipulate the database requires only three steps: get the database reference, construct the query/update criteria, and issue the request. Remember to create a collection in the console before working with the database.
The small program end
const db = wx.cloud.database();
// Insert data
db.collection('photo').add({
data: {
photo: 'cloud://tcb-xxx/05ca1d38f86f90d66d4751a730379dfa6584dde05ab4-Ma9vMN_fw658.jpg'.title: 'landscape'}});// Retrieve data
db.collection('photo').get().then((res) = > {
let data = res.data;
console.log(data);
});
/ / output
// On the applet side, _openID is automatically inserted into the database
{
photo: 'cloud://tcb-xxx/05ca1d38f86f90d66d4751a730379dfa6584dde05ab4-Ma9vMN_fw658.jpg'.title: 'landscape'._openid: 'oLlMr5FICCQJV-QgVLVzKu2312121'
}
Copy the code
Applets side database document
The service side
const app = require('tcb-admin-node');
app.init();
const db = app.database();
db.collection('photo').limit(10).get().then((res) = > {
console.log(res);
}).catch((err) = > {
console.error(err);
});
/ / output
// Since it is on the server side, other users' data can also be extracted
{
photo: 'cloud://tcb-xxx/05ca1d38f86f90d66d4751a730379dfa6584dde05ab4-Ma9vMN_fw658.jpg'.title: 'landscape'._openid: 'oLlMr5FICCQJV-QgVLVzKu4312121'
}
{
photo: 'cloud://tcb-xxx/0dc3e66fd6b53641e328e091ccb3b9c4e53874232e6bf-ZxSfee_fw658.jpg'.title: 'beauty'._openid: 'DFDFEX343xxdf-QgVLVzKu3312121'
}
{
photo: 'cloud://tcb-xxx/104b27e339bdc93c0da15a47aa546b6e9c0e3359c315-L8Px2Y_fw658.jpg'.title: 'animals'._openid: 'DFDFEX343xxdf-QgVLVzKu3412121'
}
Copy the code
Server-side database documentation
The console
You can see user-generated data in the console, and you can add, update, or delete data yourself on the console.
If there is a large amount of data, you can set indexes to provide efficient queries.
The database can also set permissions to control each collection.
Cloud function
A cloud function is a piece of code that runs in the cloud and can run back-end code in a one-click upload and deployment within the development tool without the need for an administrative server.
Developers can obtain the context of each call (appID, OpenID, etc.) in the cloud function, and obtain the naturally trusted user login state (OpenID) without maintaining complex authentication mechanism.
The small program end
wx.cloud.callFunction({
name: 'addblog'.// Cloud function name
data: { // An argument passed to the cloud function for processing
title: 'Cloud Development TCB'.content: 'Storage, data warehousing, cloud functions'
}
}).then(res= > {
console.log(res)
}).catch((err) = > {
console.error(err);
});
Copy the code
Applets end cloud function documents
The service side
const app = require("tcb-admin-node");
app.init();
app.callFunction({
name: 'addblog'.// Cloud function name
data: { // An argument passed to the cloud function for processing
title: 'Cloud Development TCB'.content: 'Storage, data warehousing, cloud functions'
}
}).then((res) = > {
console.log(res);
}).catch((err) = > {
console.error(err);
});
Copy the code
Server-side cloud function documentation
The console
After uploading the cloud function, will be listed here.
This is where you see the log every time you call the cloud function, and you can construct the parameters of the test for debugging.
Syntactic sugar
Most interfaces currently support two types of writing, namely Promise and Async/Await. This section uses callFunction as an example to introduce these two types of writing in cloud functions. Async/Await is essentially a syntactic candy based on promises, which simply translates promises into synchronous writing.
Promise
const app = require("tcb-admin-node");
app.init();
exports.main = (event, context, callback) = > {
app.callFunction({
name: 'addblog'.// Cloud function name
data: { // An argument passed to the cloud function for processing
title: 'Cloud Development TCB'.content: 'Storage, data warehousing, cloud functions'
}
}).then((res) = > {
console.log(res);
callback(null, res.data);
}).catch((err) = > {
callback(err);
});
};
Copy the code
Async/Await
const app = require("tcb-admin-node");
app.init();
exports.main = async (event, context) => {
let result = null;
try {
result = await app.callFunction({
name: 'addblog'.// Cloud function name
data: { // An argument passed to the cloud function for processing
title: 'Cloud Development TCB'.content: 'Storage, data warehousing, cloud functions'}}); }catch (e) {
return e;
}
return result;
};
Copy the code
For cloud functions, Async/Await is naturally supported because it is Node 8.9 or above, but for small applications, Polyfill is required, such as this open source project: ReGenerator
Developer Resources
As the small program · cloud development is based on the cloud development function of Tencent Cloud, so there are many developer resources on both sides of Tencent Cloud and small program, here for you to read:
- Tencent cloud developer resources and documents
- Tencent Cloud development platform official Github
- Wechat applets · Cloud development documents