Chapter 3: Implementing Custom Business Logic
This chapter will guide how to use "running JS scripts" to implement custom business logic:
- Update CloudBase Database data;
- Invoke third-party services via HTTP requests;
Writing Business Logic
After selecting and adding the "Run JS Script" node from the node list to the canvas, edit the script code.
In the code editor, you can view and select global and node variables on the left. After writing, click the "Debug Node" button on the right to quickly debug the code. You can also view relevant guidance documentation at the bottom:
Sample code as follows:
const cloudbase = require("@cloudbase/node-sdk");
const fetch = require("node-fetch");
const app = cloudbase.init({
env: cloudbase.SYMBOL_CURRENT_ENV // This can be modified to specify a CloudBase environment ID
});
const db = app.database();
// Check whether the demo collection has been created
try {
await db.collection("tcb-workflow-demo-orders").get();
} catch(e) {
await db.createCollection("tcb-workflow-demo-orders");
}
// Create a record in the cloud database collection
const result = await db.collection("tcb-workflow-demo-orders").add(wxpayTrigger.output.resource);
console.log(result);
// In addition to the CloudBase database, third-party services can also be called via HTTP requests
const apiResponse = await fetch("https://reqres.in/api/orders", { method: "POST", body: JSON.stringify(wxpayTrigger.output.resource) });
const data = await apiResponse.json();
console.log(data)
Next
Next, we will learn how to perform complete workflow debugging. Please proceed to Chapter 4: Workflow Debugging