Three cores
- Cloud database
- Provides the ability to directly add, delete, modify and query the database on the mini program side
- The database is a document storage database similar to MongoDB and is very convenient to operate.
- cloud storage
- You can directly upload, download, and delete files on the mini program.
- Comes with CDN to improve file access speed
- Temporary links can be obtained to support access outside the mini program.
- Cloud function
- Provides the ability to execute code on the server
- Contains WeChat’s natural private authentication
- Greater authority to operate databases, etc.
- Perform operations such as cloud calls and HTTP requests
Simple encapsulation of database operations
export const db = wx.cloud.database();
class NBCollection {
constructor(collectionName) {
this.collection = db.collection(collectionName);
}
add(data) {
return this.collection.add({
data,
});
}
remove(condition, isDoc = true) {
if (isDoc) {
return this.collection.doc(condition).remove();
} else {
this.collection.where(condition).remove();
}
}
update(condition, data, isDoc = true) {
if (isDoc) {
return this.collection.doc(condition).update({
data });
} else {
return this.collection.where(condition).update({
data });
}
}
query(offset = 0, size = 20, condition = {
}, isDoc = false) {
if (isDoc) {
return this.collection.doc(condition).get();
} else {
return this.collection.where(condition).skip(offset).limit(size).get();
}
}
}
export const favorCollection = new NBCollection("nb_favor");
export const likeCollection = new NBCollection("nb_like");
Cloud function example
const cloud = require('wx-server-sdk')
cloud.init()
exports.main = async (event, context) => {
const db = cloud.database()
const type = event.type
const collection = db.collection("lol")
const res = await collection.get()
return {
name: "英雄联盟",
liveRooms: res.data
}
}
const cloud = require("wx-server-sdk");
cloud.init();
exports.main = async (event, context) => {
const qrCodeRes = await cloud.openapi.wxacode.createQRCode({
width: 320,
path: "pages/cloud-database/index",
});
const wxContext = cloud.getWXContext();
const timestamp = new Date().getTime();
const openid = wxContext.OPENID;
const extension = qrCodeRes.contentType.split("/").pop();
const cloudPath = `${
timestamp}_${
openid}.${
extension}`;
const uploadRes = await cloud.uploadFile({
fileContent: qrCodeRes.buffer,
cloudPath,
});
return uploadRes;
};
const cloud = require('wx-server-sdk')
const axios = require("axios")
cloud.init()
exports.main = async (event, context) => {
const res = await axios.get("http://123.207.32.32:8000/home/multidata")
return {
recommends: res.data.data.recommend.list,
banners: res.data.data.banner.list
}
}