Using Server-Side SDK to Access CloudBase
To access various services of CloudBase in a cloud function, such as operating databases or managing cloud files, you can use the CloudBase server-side SDK.
For example, you can use the CloudBase Node.js SDK in Node.js cloud functions to call CloudBase services.
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();
};
The CloudBase server-side SDK has been integrated with cloud functions, allowing usage without manually entering keys.
Initialize the SDK
- Node.js
const cloudbase = require("@cloudbase/node-sdk");
const app = cloudbase.init({
env: cloudbase.SYMBOL_CURRENT_ENV
});
Access Cloud Database
- Node.js
const db = app.database();
exports.main = async (event, context) => {
return db.collection("todos").get();
};
Access 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
}
});
};
Get User Information
When invoking cloud functions from the client side, such as when using WeChat login authorization in mini programs or web, the user's openid
is injected into the cloud function's input parameters. Developers do not need to verify the authenticity of the openid
and can directly use it. Along with the openid
, other relevant user identity information is also injected into the cloud function.
- Node.js
- Mini Program·CloudBase
// Import the SDK
const tcb = require("@cloudbase/node-sdk");
// Initialize SDK
const app = tcb.init();
// Get user information
const userInfo = await app.auth().getUserInfo();
const {
openId, // WeChat openId, empty if not logged in via WeChat authorization
appId, // WeChat appId, empty if not logged in via WeChat authorization
uid, // unique user ID
customUserId // developer-defined unique user id, empty for non-custom login
} = userInfo;
When invoking cloud functions from the Mini Program side, developers can use the getWXContext method provided by wx-server-sdk to obtain the context of each call (appid
, openid
, etc.). This allows obtaining trusted user login states (openid
) without maintaining complex authentication mechanisms.
Example Code
// index.js
const cloud = require("wx-server-sdk");
exports.main = async (event, context) => {
// The openId, appId, and unionId obtained here are trustworthy. Note that unionId is returned only when the conditions for obtaining unionId are met.
const { OPENID, APPID, UNIONID } = cloud.getWXContext();
return {
OPENID,
APPID,
UNIONID
};
};
References
For more details, refer to: