Using server-side SDK to access CloudBase
If you need to access various services of CloudBase in cloud functions, such as operating databases or managing cloud files, you can use the CloudBase server-side SDK.
For example, you can use CloudBase Node SDK to call CloudBase services in Node.js cloud functions.
const cloudbase = require("@cloudbase/node-sdk");
const app = cloudbase.init({
env: cloudbase.SYMBOL_CURRENT_ENV
});
const db = app.database();
exports.main = async (event, context) => {
return db.collection("todos").get();
};
CloudBase server-side SDK is integrated with cloud functions and can be used without manually entering keys.
Initialize the SDK
- Node.js
const cloudbase = require("@cloudbase/node-sdk");
const app = cloudbase.init({
env: cloudbase.SYMBOL_CURRENT_ENV
});
Invoke Database
- Node.js
const db = app.database();
exports.main = async (event, context) => {
return db.collection("todos").get();
};
Invoke Cloud Storage
- Node.js
exports.main = async (event, context) => {
const fileStream = fs.createReadStream(path.join(__dirname, "demo.jpg"));
return await app.uploadFile({
cloudPath: "demo.jpg",
fileContent: fileStream
});
};
Invoke Other Cloud Functions
- Node.js
exports.main = async (event, context) => {
return await cloud.callFunction({
name: "sum",
data: {
x: 1,
y: 2
}
});
};
Obtain User Information
When calling a cloud function from the client side, such as when using WeChat login authorization in a mini program or web end, the user's openid is injected into the incoming parameters of the cloud function. Developers do not need to verify the correctness of the openid and can directly use the openid. Other relevant user identity information is also injected into the cloud function along with the openid.
- Node.js
- Mini Program CloudBase
// Reference SDK
const tcb = require("@cloudbase/node-sdk");
// Initialize SDK
const app = tcb.init();
// Obtain User Information
const userInfo = await app.auth().getUserInfo();
const {
openId, // WeChat openId, empty if not authorized via WeChat
appId, // WeChat appId, empty if not authorized via WeChat
uid, // User unique ID
customUserId // Developer-defined user unique id, empty if not using custom login
} = userInfo;
When calling a cloud function from the mini program side, developers can use the getWXContext method provided by wx-server-sdk within the cloud function to obtain the context of each call (appid, openid, etc.), without the need to maintain a complex authentication mechanism, and thus obtain a trusted user login state (openid).
Example Code
// index.js
const cloud = require("wx-server-sdk");
exports.main = async (event, context) => {
// The obtained openId, appId, and unionId are trustworthy. Note that unionId is only returned when the conditions for obtaining unionId are met.
const { OPENID, APPID, UNIONID } = cloud.getWXContext();
return {
OPENID,
APPID,
UNIONID
};
};
References
For more details, see: