DEV Community

ι™ˆζ¨
ι™ˆζ¨

Posted on

HarmonyOS5_Cloud_Function_Preloading_Guide

Hi, dear developers!πŸ‘‹

Today, let's talk about how to use the integrated device-cloud development approach for cloud functions, especially for Huawei's preloading service. This guide will walk you through the entire process from scratch, covering project creation, coding, debugging, and deployment, helping you easily master the key skills. The article is a bit long, but it's packed with valuable information, so we recommend saving it to read later!~


I. Preparation: A good start is half the battle

Before you start coding, make sure you have the following ready:

  1. Huawei Developer Account: Complete the real-name verification and log in to DevEco Studio.
  2. DevEco Studio NEXT: Install Beta1 or a higher version (download from the official website).
  3. Enable Services: Enable the Preloading service and Cloud Functions service in the AppGallery Connect console (Can't find the entrance? Just search for "Preloading" or "Cloud Functions").

II. Create an Integrated Device-Cloud Project: Set up in 5 minutes

Let's take a HarmonyOS application as an example (the process for atomic services is similar) to quickly set up an integrated device-cloud project:

  1. Create a New Project:
    • Open DevEco Studio β†’ Click Create Project on the welcome page.
    • Select the **<font style="color:rgb(255, 80, 44);background-color:rgb(255, 245, 245);">[CloudDev] Empty Ability</font>** template, then click Next.
  2. Configure Project Information:
    • Bundle Name: Must be consistent with the application package name in the AGC console (otherwise, association will fail).
    • Compatible SDK: Select 5.0.0(12) or a higher version.
    • Enable CloudDev: Checked by default (cannot be unchecked).
  3. Associate with AGC Application:
    • Select your development team, and the system will automatically match the AGC application with the same bundle name.
    • If not found, create the application in the AGC console first, then come back to associate it.
  4. Complete Creation:
    • Wait for the project to sync. You will see a **<font style="color:rgb(255, 80, 44);background-color:rgb(255, 245, 245);">CloudProgram/cloudfunctions</font>** directory, which is the home for your cloud functions!

III. Create and Configure a Cloud Function: As easy as building blocks

Now let's create a cloud function and name it **<font style="color:rgb(255, 80, 44);background-color:rgb(255, 245, 245);">my-cloud-function</font>**:

  1. Create a Function via Right-Click:
    • Go to CloudProgram/cloudfunctions β†’ Right-click β†’ New β†’ Cloud Function.
    • Enter the function name, and select the type as Cloud Function (preloading does not currently support cloud objects).
  2. Key File Analysis:
    • function-config.json: Auto-generated, do not modify it manually! This defines the function entry point and trigger (HTTP trigger by default).
    • myCloudFunction.ts: The function's entry file. Your core code goes here.
    • package.json: Dependency management. Add any third-party libraries here.

IV. Develop Function Code: From "Hello World" to practical use

Open myCloudFunction.ts, and you will see a basic template:

// Example of an entry method
export async function myHandler(event: any, context: any, callback: any) {
    const logger = context.logger; // Get the logger object
    try {
        logger.info("Received request data: " + JSON.stringify(event));
        // Your business logic goes here!
        const result = { message: "Preloading successful!", data: event };
        callback(result); // Must call callback to return the result!
    } catch (err) {
        logger.error("An error occurred!", err);
        callback({ code: 500, message: "Server is busy~" }); // Error handling
    }
}
Enter fullscreen mode Exit fullscreen mode

Key Points:

  • event: Parameters passed by the caller (e.g., request data from the client).
  • callback: Must be called explicitly to return JSON-compatible data or an error object.
  • Logging: Use <font style="color:rgb(255, 80, 44);background-color:rgb(255, 245, 245);">logger.info()</font> and <font style="color:rgb(255, 80, 44);background-color:rgb(255, 245, 245);">logger.error()</font> to record runtime logs for troubleshooting.

V. Debugging Functions: Local vs. Remote

1. Local Debugging (for quick validation):

  • Step1: Right-click the function directory β†’ Debug 'my-cloud-function'.
  • Step2: Open the Cloud Functions Requestor tool (View β†’ Tool Windows).
  • Step3: Select the function, set the environment to Local, enter test data β†’ Click Trigger.
  • Result: View logs in the console. In Debug mode, you can even set breakpoints for line-by-line debugging!

2. Remote Debugging (to simulate the real environment):

  • Step1: First, deploy the function to AGC (Right-click the function β†’ Deploy).
  • Step2: In the Cloud Functions Requestor tool, set the environment to Remote.
  • Step3: Trigger the call. The results and logs will be displayed directly in the tool.

VI. Deploying Functions: One-click to the cloud

  1. Single Deployment: Right-click the function directory β†’ Deploy. A success message in the status bar indicates completion.
  2. Batch Deployment: Deploy the entire cloudfunctions directory (suitable for multi-function projects).

Post-Deployment Management:

  • Log in to the AGC console β†’ Go to Cloud Functions β†’ View the list of deployed functions.
  • You can monitor invocation counts, logs, configure triggers, and even quickly roll back to previous versions!

VII. Preloading Practical Tips: Speed up your application

In a preloading scenario, you can preload resources during function initialization:

// Example: Preloading a configuration file
let configCache: any;

export async function myHandler(event: any, context: any, callback: any) {
    if (!configCache) {
        // Load configuration on the first call
        configCache = await loadConfigFromDB(); // Assume reading from a database
    }
    // Process the request using the cached configuration
    const result = processRequest(event, configCache);
    callback(result);
}
Enter fullscreen mode Exit fullscreen mode

Conclusion: Let cloud functions give your application wings

Through integrated device-cloud development, we can not only quickly build cloud functions but also seamlessly integrate with HarmonyOS applications to achieve advanced features like preloading. If you encounter any problems during your practice, feel free to leave a comment or ask questions in the Huawei Developer Community (remember to add the #CloudFunctions tag!).

Finally, thank you for your patient reading! πŸš€ If you found this helpful, please give it a like or share it with more friends~ See you next time!


Happy coding, and may your code be bug-free! 😊

Top comments (0)