1 -> Development process
SCF is a serverless computing service that can elastically scale in functions based on their actual traffic. You only need to focus on the business logic and develop functions related to uploading business modules, and SCF can automatically complete resource allocation, code deployment, load balancing, etc., which not only improves the speed of development and launch of functions, but also ensures the high availability of functions.
Use DevEco Studio to integrate devices and clouds.
The overall process of developing SCF under the cloud-side project is as follows:
Create and configure functions: You can directly create functions in DevEco Studio, configure entry points for functions, and triggers for calls.
Develop a function: After the function is created and configured, you can start writing the function business code.
Debugging functions: You can debug functions to test whether the function code runs properly.
Deploy functions: After the function code is developed and debugged, the function can be deployed to the AGC cloud, supporting single deployment and batch deployment.
illustrate
Generally, it is recommended that you deploy functions to the cloud after debugging them correctly, but in some business scenarios, you need to deploy functions before debugging. Perform the following operations based on your business needs.
2 -> Create and configure the function
You can directly create functions in DevEco Studio and configure triggers for function calls.
2.1 -> Create a function
- Right-click on the cloudfunctions directory and select New > Cloud Function.
- Select the Cloud Function Type in the Select the Cloud Function Type column, enter the function name (e.g. my-cloud-function), and click OK.
The function name must be between 2 and 63 characters in length and can only be lowercase letters, digits, and hyphens (-), with the first character being lowercase and ending with a hyphen (-).
The new "my-cloud-function" function directory is generated in the cloudfunctions directory, which mainly contains the following files:
Function configuration file "function-config.json"
Function entry file "myCloudFunction.ts"
Dependency profile "package.json"
2.2 -> Configure functions
After the function is created, you can configure the trigger in the function-config.json configuration file and call the function based on the trigger conditions exposed by the trigger.
illustrate
functionType indicates the function type, 0 indicates the cloud function, and 1 indicates the cloud object. The value of functionType is automatically generated at the time of creation and cannot be manually modified, otherwise the SCF deployment will fail.
Currently, SCF only supports HTTP triggers, and the HTTP trigger configuration is automatically completed for you in the function-config.json file. Once a function configured with HTTP triggers is deployed to the cloud, your application can call the function through Cloud Foundation Kit.
note
If you want to update a trigger after the function is deployed, delete the previous trigger configuration and add a new trigger configuration, otherwise the update will not take effect.
{
"type": "http",
"properties": {
"enableUrlDecode": true,
"authFlag": "true",
"authAlgor": "HDA-SYSTEM",
"authType": "apigw-client"
}
}
type: Trigger type, set to http.
properties: the trigger property, which is listed in the following table.
3 -> Develop functions
After the function is created and configured, you can start writing the function business code.
- Open the function entry file and write the function code.
In this example, we use the function "my-cloud-function" as an example to construct a function that returns timestamps.
/**
* Describe the basic method of Cloud Functions
*/
let myHandler = function(event, context, callback, logger){
// example of display environment variables
let env1 = context.env.env1;
// example of display logs
logger.info("Test info log");
logger.warn("Test warn log");
logger.debug("Test debug log");
logger.error("Test error log");
logger.info("--------Start-------");
try {
let startTime = new Date().getTime();
let endTime = startTime;
let interval = 0;
startTime = process.uptime() * 1000;
// print input parameters and environment variables
logger.info("request: " + JSON.stringify(event.request));
logger.info("env1: " + env1);
endTime = process.uptime() * 1000;
interval = endTime - startTime;
logger.info("intervalTime: " + interval);
logger.info("--------Finished-------");
let res = new context.HTTPResponse(context.env, {
"res-type": "context.env",
"faas-content-type": "json",
}, "application/json", "200");
res.body = {"intervalTime": interval};
callback(res);
} catch (error) {
logger.error("--------Error-------");
logger.error("error: " + error);
callback(error);
}
};
module.exports.myHandler = myHandler;
note
SCF and SCF are independent of each other, and when deployed to the SCF side, only the files in the selected SCF directory will be deployed. /anotherDirectory/xxx'. If there are multiple SCF configurations, we recommend that you store them in the TencentDB for the Common Function and query the common configurations through the TencentDB Server API. You can also combine multiple SCFs into a single cloud object, and turn a public configuration into a private configuration of a cloud object.
- (Optional) If there are dependencies in the function, you can add the required dependencies under "dependencies" in the "package.json" file, and then click "Sync Now" in the upper right corner.
illustrate
You can also install dependencies by right-clicking on the package.json file and selecting the "Run 'npm install'" menu.
All installed dependencies are stored in the "node_modules" directory of the current function.
4 -> Debug Functions
After the function is developed, you can debug the function to verify that the function code is running properly.
Currently, DevEco Studio function debugging supports local and remote calls.
Debugging Functions by Local Call: Debug locally developed functions in DevEco Studio. It supports single debugging and batch debugging, and supports two modes, Run and Debug, with rich debugging functions, and is often used in the process of function development or problem locating.
Debugging a function by calling it remotely: Deploy the function to the AGC cloud and then call the function in DevEco Studio. This method is mainly used to test the running of functions in the cloud, or to supplement the test of problems that cannot be found in the local invocation mode due to various factors.
4.1 -> Prerequisites
Make sure you're logged in.
If your project has code logic that involves SCF calling ApsaraDB, you need to deploy the entire cloud project to AGC Cloud before debugging, otherwise there will be no relevant data and environment variables in the cloud.
4.2 -> Debug functions by calling them locally
You can debug locally developed functions in DevEco Studio, support single debugging and batch debugging, and support both run and debug modes.
The process of single debugging and batch debugging is the same, but the only difference is that a single debugging starts local debugging for only one function at a time, and then only that function can be called; Batch debugging starts local debugging for all functions in the "cloudfunctions" directory at once, and then calls each function one by one.
The difference between Run mode and Debug mode is that Debug mode supports the use of breakpoints to track the running of functions, while Run mode does not.
The following section uses the my-cloud-function in Debug mode as an example to describe how to debug a local function in DevEco Studio.
- Right-click the "my-cloud-function" function directory and select "Debug 'my-cloud-function'".
illustrate
Debug directly from the current path, using the default Debug configuration, you can also customize the Debug configuration. After the custom debug configuration is created, the custom debug configuration will be used first.
If you want to debug multiple functions in batches, right-click the cloudfunctions directory and select Debug Cloud Functions to start all functions in the directory. If there are both SCFs and Cloud Objects in the "CloudFunctions" directory, all SCFs and Cloud Objects will be started.
- In the CloudFunctions window at the bottom of the notification bar, view the debug logs. If the message "Cloud Functions loaded successfully" is displayed, the function is successfully loaded into the local HTTP server and the corresponding function URI is generated.
- If you need to set a breakpoint for debugging, select a valid line of code to set a breakpoint in the function code, and click the left mouse button after the line number (as shown in line 15 in the figure below) to set the breakpoint (the red dot in the figure below).
When a breakpoint is set, debugging can break at the breakpoint and highlight the line.
- Select "View > Tool Windows > Cloud Functions Requestor" in the menu bar and use the Cloud Functions Requestor to trigger a function call.
- In the Cloud Functions Requestor panel that appears, set the trigger event parameters.
Cloud Function: Select the function to be triggered, in this example, the function my-cloud-function.
Environment: Select the environment in which the function is called. In this case, Local is selected to indicate a local call.
Event: Enter the event parameters, which are the request body data in JSON format.
- (Optional) Click "Save" to save the current triggering event.
Click on the top right corner
You can expand the saved trigger event, and then you can directly click "Load" to load the event. For trigger events that do not need to be saved, you can also click "Delete" to delete.
- Click "Trigger", which will trigger the execution of the user's function code. The execution result is displayed in the Result box, and the debugging log is printed in the cloudfunctions window.
illustrate
The Logs panel to the right of the Result box is only used when debugging a function by calling it remotely.
- (Optional) If environment variables are configured, you can pass the variable information to the function execution environment for reading the function when it is running.
logger.info(context.env.name);//name为环境变量名称
As shown in the following figure, the environment variable env1 is configured for the my-cloud-function function, and the value value1 of the environment variable env1 can be accessed.
4.3 -> Debugging functions by calling them remotely
You can also deploy functions to the AGC cloud, and then call the cloud functions in DevEco Studio to test the operation of the functions in the cloud, or to supplement the problems that cannot be found in local debugging due to various factors.
Refer to Deployment Functions to deploy the functions that need to be debugged to the AGC Cloud.
(Optional) If the function code involves accessing environment variables, you need to click the function name in the function list on the AGC Portal to configure the value of the environment variable for the function to read and use at runtime.
- Select "View > Tool Windows > Cloud Functions Requestor" in the menu bar and use the Cloud Functions Requestor to trigger a function call.
- In the Cloud Functions Requestor panel that appears, configure the trigger event parameters.
Cloud Function: Select the function to be triggered, in this example, the function my-cloud-function is used as an example.
Environment: Select the environment in which the function is called. If you select Remote, you can make a remote call.
Event: Enter the event parameters, which are the request body data in JSON format.
- Click "Trigger", the execution of the user's function code will be triggered, and the execution result will be displayed in the "Result" box.
- Click the Logs tab to view the printed logs. Modify the function code, redeploy the function, and then execute the remote call again until there is no problem.
- Refer to steps 1~5 to debug other functions.
5 -> Deploy the function
After the function code is developed, you can deploy the function to the AGC cloud, which supports single deployment or batch deployment.
A single deployment deploys only the selected functions, while a batch deployment deploys all functions in the entire cloudfunctions directory to AGC Cloud at the same time.
The following section uses the my-cloud-function as an example to describe how to deploy a function.
- Right-click the my-cloud-function directory and select Deploy 'my-cloud-function'.
illustrate
If you want to deploy multiple functions in batches, right-click the cloudfunctions directory and select Deploy Cloud Functions to deploy all functions in the directory. If both SCF and CF exist in the "cloudfunctions" directory, the SF and CF objects will be deployed to AGC Cloud together.
- You can view the function packaging and deployment progress on the right side of the status bar at the bottom.
Wait patiently until the "Deploy successfully" message appears, indicating that the current function has been successfully deployed.
- Select Tools > CloudDev in the menu bar.
- In the CloudDev panel that opens, click Go to console under Serverless > Cloud Functions to enter the SCF page of the current project.
- Check that the "my-cloud-function" function has been successfully deployed to AGC Cloud, and the function name is the same as the function directory name of the local project.
After the deployment is successful, you can call SCF from the device.
Top comments (0)