Skip to main content

sdk

Accessing CloudBase Using Server-side SDK

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 the CloudBase Node SDK to invoke 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();
};
Tip

CloudBase server-side SDK has been integrated with cloud functions and can be used without manually entering keys.

Initialize the SDK

const cloudbase = require("@cloudbase/node-sdk");
const app = cloudbase.init({
env: cloudbase.SYMBOL_CURRENT_ENV
});

Invoke the database

const db = app.database();
exports.main = async (event, context) => {
return db.collection("todos").get();
};

Invoke cloud storage

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

exports.main = async (event, context) => {
return await cloud.callFunction({
name: "sum",
data: {
x: 1,
y: 2
}
});
};

Obtain User Information

When invoking cloud functions from the client side, such as during WeChat login authorization in mini programs or on the 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 use this openid directly. Along with the openid, other relevant user identity information is also injected into the cloud function.

// Import the SDK
const tcb = require("@cloudbase/node-sdk");
// Initialize the 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 unique user id, empty if not custom login
} = userInfo;

Reference

For more details, refer to: