Using the Cloud DB JavaScript Server SDK in Cloud Functions - Huawei Developers

With Cloud Functions, you can configure a CLOUDDB trigger to call a function when data is entered, deleted, or modified in Cloud DB.
The Cloud DB service has been released with a JavaScript Server SDK, which can be used in the Node.js environment that the Cloud Functions service supports. In this article, I will elaborate on how to enter and query data with the Cloud DB JavaScript Server SDK in Cloud Functions.
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Enabling Required Services​You need to enable two services.
First of all, sign in to AppGallery Connect and perform the following operations:
Enable Cloud Functions. Click My projects, click your project card, and go to Build > Cloud Functions. On the Cloud Functions page, click Enable now. Click + New Function to create a function.
Enable Cloud DB. Click My projects, click your project card, and go to Build > Cloud DB. On the Cloud DB page, click Enable now and then create an object type and a Cloud DB zone.
Configuring the JavaScript Server SDK of Cloud DB​Here, I will use the src file in the Huawei service demo to demonstrate how the JavaScript Server SDK is configured. You can also download the file and use it for your own file from GitHub.
Then you need to do the following in AppGallery Connect:
Export an object type.​On the Cloud DB page, export the BookInfo object type to a JS file, and then add it to the model directory of your project.
Download the authentication credential.​Go to Project settings > Server SDK. On the Server SDK tab page, click Create for API client first, and then click Download credential to download the authentication credential. Finally, add it to the model directory of your project
Modify the path to the credential.​You need to modify the path to the credential as it was saved to the model directory. In the CloudDBZoneWrapper.js file (use the _dirname method to obtain the file), modify the initialization code as follows:
Code:
let api_client_name = "agc-apiclient-testDB.json";
let path = require('path');
let api_client_path = path.join(_dirname,api_client_name);
agconnect.AGCClient.initialize(agconnect.CredentialParser.toCredential(api_client_path));
Configure a handler.​You can either use the Start.js file as the handler by default or create a new one. For example, the inde.js file is created as a handler. The sample code is as follows:
Code:
const CloudDBZoneWrapper = require("./model/CloudDBZoneWrapper.js");
let myHandler = async function(event, context, callback, logger) {
logger.info(JSON.stringify(event));
logger.info("event start");
const cloudDBZoneWrapper = new CloudDBZoneWrapper();
const bookInfo = cloudDBZoneWrapper.getSingleBook();
// Update and insert a list of books.
await cloudDBZoneWrapper.upsertBookInfos(bookInfo);
let result = {"message":"Run Success"}
callback(result);
}
module.exports.myHandler = myHandler;
Packaging Your Project and Configuring a Trigger​You need to package your project, upload it to Cloud Functions, and test it with events. The handler file should be saved in the root directory.
Sign in to AppGallery Connect and go to the Cloud Functions page. Upload your package and set the name of the handler to index.myHandler
Configure a CLOUDDB trigger. Click + Add Trigger and configure the type, Cloud DB zone, and object type for the trigger.
Testing the Function​In AppGallery Connect, go to Cloud Functions > Test.
Configure a trigger event according to the documentation
If you need to configure a data insertion event, add the following sample code.
Code:
{
"records": [{
"before": null,
"after": {
"id": "11111",
"bookName": "user1"
}
}],
"objectTypeName": "BookInfo",
"naturalStoreName": "QuickStartDemo"
}
Check the test result.
Reference​Cloud Functions
Defining a programming model
Cloud DB JavaScript Server SDK

Related

Huawei Wallet Kit -Server Side Tickets and All-in-one pass Creation

This is originally from HUAWEI Developer Forum
Forum link: https://forums.developer.huawei.com/forumPortal/en/home​
Introduction
HUAWEI Wallet Kit providing users to claim passes of merchants, like loyalty cards, gift cards, coupons, boarding passes, event tickets, and transit passes. It provides easy-to-access digital passes on an integrated platform. It enables user save their cards into mobile phones for convenient. The interaction between apps and users via location based notifications.
Integration Process.
The Wallet Kit integration process consists following steps
1. Generating Public and Private Keys
2. Adding Pass type on the AGC
3. Running the Server Demo code
4. Running the Client Demo code
5. View card adding status
Step-1: Check Below Link to generate keys & App Configuration in AGC:
LINK: https://forums.developer.huawei.com...d=0201242460338530108&fid=0101187876626530001
· Let’s see how to apply new wallet.
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
· Now will see how to create Flight ticket.
· Service type consists 3 types
1. Card
2. Coupon
3. Ticket
· Service item will change based on service type
· Service name should be Unique
· Service Id should be unique it will start will always hwpass
· Public key we need to get it from RSAUtils
· Click next button and save details. The service application procedure is now complete. After applying for the service, you can view, edit, and delete it on the HUAWEI Wallet Kit service application page
Step-2: Server Side Integration:
Download server demo code check below link.
Link: https://developer.huawei.com/consumer/en/doc/development/HMS-Examples/wallet-sample-code
1. Download maven dependency.
2. Configure your project into IntelliJ IDEA
3. Download required dependencies and import
4. Sync your project
5. Open release.config.properties and replace appId & secret Key
6. Compile project using terminal mvn clean compile
7. After completion of compilation automatically Target folder will generate
Follow below steps
Copy hmspass folder in the config directory, paste into the target/classes directory.
You can run the source code, you can run mainly java files in the Test folder.
Check below steps and modify accordingly.
· The file ends with ModelTest provides the examples of adding, modifying and pass models.
· The file name ends with InstanceTest provides the examples of adding, modifying and pass instances.
Step-3: Generate Pass Model:
· Open FlightModel.json file
· PassTypeIdentifier is unique which you mentioned service Id in AGC both needs to match
· You have to modify passTypeIdentifier and passStyleIdentifier when we add card types on the AGC PassStyleIdentifier field is unique.
· After completion of modify execute createFlightModel()
· Open the HwFlightModelTest file and Run CreateFlightModel() method
Code:
Test
public void createFlightModel() {
System.out.println("createFlightModel begin");
// Read an example flight model from a JSON file.
String objectJson = CommonUtil.readWalletObject("FlightModel.json");
HwWalletObject hwWalletObject = JSONObject.parseObject(objectJson, HwWalletObject.class);
String modelId = hwWalletObject.getPassStyleIdentifier();
System.out.println("modelId is: " + modelId);
String instanceId = hwWalletObject.getSerialNumber();
// Set parameters of the flight model you want to create. Flight instances belong to this model share these
// parameters.
WalletBuildService walletBuildService = new WalletBuildServiceImpl();
HwWalletObject requestData = walletBuildService.createHwWalletObject(objectJson, instanceId, modelId);
// Validate the parameters.
boolean validateModel = HwWalletObjectUtil.validateWalletModel(requestData);
if (validateModel) {
// Post the new flight model to the wallet server.
String urlParameter = "flight/model";
HwWalletObject flightModel = walletBuildService.postHwWalletObjectToWalletServer(urlParameter, requestData);
System.out.println("createFlightModel JSON is: " + CommonUtil.toJson(flightModel));
System.out.println("createFlightModel end");
}
}
This is not all. For full content, you can visit https://forums.developer.huawei.com/forumPortal/en/topicview?tid=0201254289105300220&fid=0101187876626530001
This is a great solution for wallet and loyalty apps that want to stay away from GMS.

HUAWEI Analytics Kit: Data Export

Use Cases
HUAWEI Analytics Kit provides a server API for you to export event data collected on devices and import the data to your BI system for unified data analysis. After the export is complete, Analytics Kit asynchronously uploads the exported data to the Object Storage Service (OBS) and then returns the export result and data storage path to your app server by sending an HTTPS POST request to call its callback API. To ensure data security, the download link will become invalid after 2 hours.
The following table describes the export states that are currently supported.
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
The following table lists the data filter criteria.
Getting Started
Setting the Callback API
Sign in to AppGallery Connect. Go to My projects > HUAWEI Analytics > Management > Analysis setting, and select Set Callback API to set related parameters.
1. Configure the callback API URL for receiving the data download link.
2. Configure the HTTPS certificate.
3. Click Test callback to test the function of the callback API. After the test is successful, click Submit to complete the callback API configuration.
Development Guide
Before developing a callback API, you need to prepare a public network domain name and an API that can receive POST requests. Ensure that the POST API has an HTTPS certificate.
The development procedure is as follows:
1. Develop the callback API. In the sample code, the domain name is habackup.hwcloudtest.cn, which is accessible by your server.
Code:
@RequestMapping(value = "/agc/analytics/callback", method = RequestMethod.POST)
public ResultResp callback(@RequestBody @Valid ExportDataCallbackReq req) {
ResultResp result = new ResultResp();
// Receive the callback after the export task is generated.
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("the download url: {}", req.getFilePath());
}
// Obtain the download link to continue.
result.setResultCode("0");
result.setResultMsg("success");
return result;
}
Requested object:
Code:
public class ExportDataCallbackReq implements Serializable {
private static final long serialVersionUID = -8014011591749838257L;
@JsonProperty("request_id")
private String requestId;
@JsonProperty("app_id")
private String appId;
@JsonProperty("status")
private String status;
@JsonProperty("file_path")
private String filePath;
@JsonProperty("status_time")
private String statusTime;
}
2. Go to HUAWEI Analytics > Management > Analysis setting to configure the callback API.
3. Call the public API to obtain the token
POST request:
URI: https://oauth-login.cloud.huawei.com/oauth2/v2/token
Header:
Code:
Content-Type:Application/x-www-form-urlencoded
Body:
Code:
grant_type:client_credentials
client_id:100664247
client_secret:170e4ecb457bd73fa7c977de976274a7
Response:
Code:
{
"access_token": "CV6qeoJReXe+YfDRQomDe9VW1B6fzIH1QU260T94x4RBLUSZRjTRIcY7IngF1cPIEYaPhJCjVNOxrhvAo49Ay/Ukkf+p",
"expires_in": 3600,
"token_type": "Bearer"
}
4. Start data export.
POST request:
URI: https://datacollector-drcn.dt.hicloud.com/analytics/export/raw_data_requests/v2
Header:
Code:
Authorization:Bearer CV6qeoJReXe+YfDRQomDe9VW1B6fzIH1QU260T94x4RBLUSZRjTRIcY7IngF1cPIEYaPhJCjVNOxrhvAo49Ay\/Ukkf+p (token_type + space + access_token, obtained from the token response)
x-App-id:10066424
Content-Type:Application/json
x-product-id:9105163812218569643
Body:
Code:
{
"date_range": {
"start_date": "2020-2-29",
"end_date": "2020-3-10"
},
"file_format": "csv",
"filters": []
}
Response:
Code:
{
"result_code": "0",
"result_msg": "success"
}
5. View the export status.
Go to My projects > HUAWEI Analytics > Management > Data export.
6. After the export is complete, the Analytics Kit automatically calls the callback API to obtain the export result. Obtain the download link from the file_path field. The link is effective in 6 hours.
7. View the export result. If the following information is displayed, the export is successful.
Code:
[
{
"request_id": "c0b41debe8064c54ab200d30907f40c5",
"App_id": "100664247",
"status": "EXPORTED",
"file_path": "https://nsp-ha-gdpr-drcn.obs.cn-north-2.myhuaweicloud.com/20200430_14_c0b41debe8064c54ab200d30907f40c5.csv?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=F9WBKUUWDQODJO4FQMBF%2F20200430%2Fcn-north-2%2Fs3%2Faws4_request&X-Amz-Date=20200430T073623Z&X-Amz-Expires=86400&X-Amz-SignedHeaders=host&X-Amz-Signature=9145e80d51e21cd295861a5a0688bbcfbf8805e071cd8b98e08b5eacf2171fdb",
"status_time": "2020-04-30 07:37:02"
}
]
For details about the fields int he exported file, please refer to Description of Fields in the Export Data File.

Java Client for HMS Product Management Service API

More information like this, you can visit HUAWEI Developer Forum​
Let’s say that you need to create an in-app product on Huawei AppGallery Connect. To do this, you sign in to AppGallery Connect, browse to your application, go to In-App Purchase, specify product information, and release the product. However, in reality, an application never have one but ten or twenty in-app products instead. In other words, you have to repeat the boring procedure mentioned above ten or twenty times! Don’t panic yet. This article will show you how to automate such mundane work using Product Management Service API.
The Product Management Service (PMS) API is a part of AppGallery Connect API, a HUAWEI’s alternative to Google Play Developer API. It provides RESTful APIs that can be used to create and update in-app product and promotion information. Utilizing this API, the automation tool (in Java) provided in this article will help you manage in-app product fast and precisely. Let’s examine how this tool works and its features.
Creating an API client
Accessing PMS API, as well as any other Connect APIs, requires authorization from the AppGallery Connect server in advance using either of the following modes:
API client mode: In this mode, an API client is used to authenticate and get access to AppGallery Connect APIs
OAuth client mode: In this mode, access to AppGallery Connect APIs is authorized by Huawei developer accounts. This mode is appropriate for developing a third-party IDE or development tool that needs to be connected to AppGallery Connect. This mode will not be discussed in this article
The tool I created utilized API client mode to call the AppGallery Connect API. Therefore, to be able to use the tool, you need an API client. The procedure of creating an API client is as follows:
Sign in AppGallery Connect and select Users and Permissions
Go to API Key > Connect API from the navigation tree on the left and click Create.
Set Name to a customized client name, set Roles to the corresponding role, and click Confirm. For details about roles and permissions, please refer to Roles and Permissions
After the client is successfully created, record the values of Client ID and Key in the client information list. You will need these values to run the tool later.
How to use the automation tool?
The automation tool is a Maven project, developed in Eclipse IDE. You will need to download and install Eclispe IDE for Java Developers (https://www.eclipse.org/downloads/packages/release/2020-06/r/eclipse-ide-java-developers) if you haven’t already. Then, download the tool from the github repos (https://github.com/buiquanghuy23103/PMS-demo). Once you had the tool and the IDE, let’s run it by following the instructions below:
Open Eclipse IDE. Go to File > Import > Maven > Existing Maven Projects. Then click Next.
Browse to the directory of the sample project
Select pom.xml in the Projects box and click Finish.
Open Package Explorer (Window > Show View > Package Explorer) and navigate to src > test > PmsApiDemo.java. In this file, provide Client ID, Client Key and App ID
To run the tool, from the app bar of Eclipse IDE, go to Run > Run
Creating a product
You can create new in-app products in few seconds with PMS. Go to projectDirectory > src > test > CreateProducts.java to specify product information, and then call CreateProducts.createNewProducts() in PmsApiDemo.java. Please note that product information has to follow the rules in ProductImportInfo. Otherwise, the tool will throw an exception.
Code:
public static void main(String[] args) throws InvocationTargetException, IllegalAccessException {
String token = GetToken.getToken(domain, clientId, clientSecret);
CreateProducts.createNewProducts(domain, clientId, token, appId);
}
Get product information
You can easily view information of any in-app products in AppGallery Connect through PMS. All you need to do is calling GetIapProductInfo.getProductInfoDetail() in PmsApiDemo.java.
Code:
public static void main(String[] args) throws InvocationTargetException, IllegalAccessException {
String token = GetToken.getToken(domain, clientId, clientSecret);
GetIapProductInfo.getProductInfoDetail(domain, clientId, token, appId, productNo);
}
The response will be in JSON format as follow:
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Update product information
You can also update product information in the AppGallery through PMS. Go to UpdateProduct. generateUpdateRequest() to update your product information, and then call UpdateProduct.update() in PmsApiDemo.java.
Code:
public static void main(String[] args) throws InvocationTargetException, IllegalAccessException {
String token = GetToken.getToken(domain, clientId, clientSecret);
UpdateProduct.update(domain, clientId, token, appId, productNo);
}
Apart from these endpoints I integrate, you can also check out the other features of the PMS API here:
https://developer.huawei.com/consumer/en/doc/development/AppGallery-connect-Guides/agcapi-pms-api-manage_product_promotion

Huawei Flight Booking Application (Cloud DB) – Part 8

Introduction
Flight booking app allows user to search and book flight. In this article, we will integrate Huawei Cloud DB into demo flight booking application.
Huawei Cloud DB is a computing platform that provides functionality of traditional database with cloud computing. The cloud DB ensures data availability, reliability, consistency, security and enables seamless data synchronization between the device and cloud, and supports offline application operations, helps developers quickly develop device-cloud and multi-device synergy applications. Cloud DB builds the Mobile backend as a service capability for the AppGallery Connect platform. This provides developer to focus on application services, delivering the efficient product.
For prerequisite and set up, refer to part 1.
Usecase
1. Once user books the flight from the app, we will store flight booking information in cloud DB.
2. User can navigate to Itinerary Screen from navigation drawer to see all the flight booked by him in past.
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Permissions
By default, users who access Cloud DB from the AppGallery Connect console or cloud function have all permissions, as they are assigned with administrator role.
Everyone : All users. This role has only query permission granted.
Authenticated user: Users who have passed the AppGallery Connect login.This role has the query permission by default and upsert and delete permission can be granted.
Data creator: Authenticated users who create data. Data creators can upsert or delete the data created only by themselves. The information about data creator is stored in data table system records. This role has all permissions by default and can customize the permissions.
Administrator: Developers who access Cloud DB from the AppGallery Connect console . This role has all permissions by default and can customize the permissions.
Accessing Cloud DB
Since Cloud DB is in beta stage, developers need to send a mail to activate this service in their app. Developer needs to create Huawei developer account. Once account created, developers need to create an app in App Gallery connect. After completing all the necessary steps, developer have to request the activation of the service by sending an e-mail to [email protected] with the subject as "[Cloud DB]-[Company name]-[Developer account ID]-[App ID]". To access the app ID, see Querying App Information. Usually it takes 1 to 3 days for activation, once activated , developer can integrate cloud DB service in their app.
Getting started with Cloud DB
1. Log in to AppGallery Connect and select My Projects.
2. Select Application for which you want to create object types.
3. Choose Build > Cloud DB from left panel.
4. Click on Enable now.
5. Click Add to create object type.
6. Set Object Type Name to EaseMyFlight, and click Next.
7. Click on Add fields , add the fields and click Next.
8. Click Add Index, set Index Name and Indexed Field, and click Next.
9. Add permissions as follows and click Next. (For Everyone , upsert and delete access is not allowed).
10. Click Ok. Object types are created and displayed in the object type list.
11. Click Export. Select JAVA as export file name. Enter the package name of JAVA file. package name can contain Letters A–Z or a–z, Digits 0–9, Special characters _ and .
12.Click Export. The file that contains all object types will be downloaded. Add the exported JAVA file in your project.
Cloud DB Zone
1. Log in to AppGallery Connect and select My apps.
2. Select Application for which you want to create object types.
3. Choose Build > Cloud DB from left panel.
4. Click Cloud DB Zones tab.
5. Click Add to navigate to the Cloud DB zone creation page.
6. Enter easeMyFlightZone in the Cloud DB Zone Name text box.
Development
Prerequisites
Auth Service has to be integrated. Follow this tutorial to integrate Auth Service.
1. Add cloud DB SDK dependecy in app- level build.gradle.
Code:
// Add the Cloud DB SDK.
implementation 'com.huawei.agconnect:agconnect-database:1.2.1.301'
2. Add compatibility mode to JDK 1.8 in app- level build.gradle.
Code:
compileOptions {
sourceCompatibility = 1.8
targetCompatibility = 1.8
}
3. Initialize AGConnectCloudDB in Application class.
Code:
public class EaseMyFlightApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
initAGConnectCloudDB(getApplicationContext());
}
public static void initAGConnectCloudDB(Context context) {
AGConnectCloudDB.initialize(context);
}
}
4. Get the instance of AGConnectCloudDB and create object types.
Code:
mCloudDB = AGConnectCloudDB.getInstance(); mCloudDB.createObjectType(ObjectTypeInfoHelper.getObjectTypeInfo());
5. Create the Cloud DB zone configuration file and open the Cloud DB zone.
Code:
mConfig = new CloudDBZoneConfig("easeMyFlightZone", CloudDBZoneConfig.CloudDBZoneSyncProperty.CLOUDDBZONE_CLOUD_CACHE,
CloudDBZoneConfig.CloudDBZoneAccessProperty.CLOUDDBZONE_PUBLIC);
mConfig.setPersistenceEnabled(true);
try {
mCloudDBZone = mCloudDB.openCloudDBZone(mConfig, true);
} catch (AGConnectCloudDBException e) {
Log.w(TAG, "openCloudDBZone: " + e.getMessage());
}
6. Writing Data
Data can be entered either manually from App Gallery Connect(administrator or data creater) or programmatically(authorized user) by using cloud DB SDK , if user has the permission. If same value in primary key is used, data will be modified.
Code:
public void insertDataToCloudDB(EaseMyFlight info) {
if (mCloudDBZone == null) {
Log.w(TAG, "CloudDBZone is null, try re-open it");
return;
}
CloudDBZoneTask<Integer> upsertTask = mCloudDBZone.executeUpsert(info);
upsertTask.addOnSuccessListener(new com.huawei.agconnect.cloud.database.OnSuccessListener<Integer>() {
@Override
public void onSuccess(Integer integer) {
Log.w(TAG, "upsert " + integer + " records");
}
}).addOnFailureListener(new com.huawei.agconnect.cloud.database.OnFailureListener() {
@Override
public void onFailure(Exception e) {
Log.e(TAG, "Insertion failed : "+ e.getMessage());
e.printStackTrace();
}
});
}
More information, you can visit https://forums.developer.huawei.com/forumPortal/en/topicview?tid=0201388320242800533&fid=0101187876626530001
Does it supports BLOB Data Type ?

How Can I Quickly Integrate Cloud Functions of AppGallery Connect into My Cocos-based App?

1. Environment
SDK Version:agconnect-storage:1.3.0.300
Platform:Cocos Creator
Device:HUAWEI P40 Pro
AppGallery Connect:
https://developer.huawei.com/consumer/en/service/josp/agc/index.html
2. Enabling and Configuring Cloud Functions in AppGallery Connect
Note: Currently, Cloud Functions is still under beta state. To use the service, you need to send an email for application. For details, check:
https://developer.huawei.com/consum...allery-connect-Guides/agc-cloudfunction-apply
1. Create an app first and add it to a project, or select an app from the project list on the My projects page in AppGallery Connect.
Under the project, go to Build > Cloud Functions, and click Enable now.
2. Create a function based on the description in the following codelab.
https://developer.huawei.com/consumer/en/codelab/CloudFunctions/index.html#4
3. Create an HTTP trigger and save the suffix of the value of Trigger URL in the Details area as the trigger identifier of future client requests.
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
3. Integrating the Cloud Functions SDK in Cocos Creator
1. Integrate the SDK.
Official documentation:
https://docs.cocos.com/creator/manual/en/cocos-service/agc-applinking.html
1. On the Service panel of Cocos Creator, find Cloud Functions. Currently, the Cloud Functions SDK supports only the Android platform.
2. Before integrating a service, you need to associate the service with an app. Click Association. In the dialog box that is displayed, click Create. The Cocos console is displayed.
3. On the Cocos console, create a game.
4. Go back to Cocos Creator and create, refresh, or select an association.
5. Return to the Cloud Functions page, and enable the service.
2. Download the JSON file.
1. Go to Project settings in AppGallery Connect and download the latest agconnect-services.json file.
2. Save the downloaded agconnect-services.json file to the settings directory in your Cocos project.
4. Configuring the UI Layout
Configure buttons for triggering a cloud function, obtaining the timeout interval, and setting the timeout interval separately.
5. Cloud Functions Development
1. Initialize Cloud Functions in the start block.
Code:
start () {
this._func = huawei.agc.func.funcService;
},
2. Call Cloud Functions with input parameters.
Code:
callWithParam:function() {
this._func.wrap("testcodelab-$latest").call((err, data) => {
if (err !== null) {
console.log("Cloud Function", `error: ${JSON.stringify(err)}`);
}
console.log("Cloud Function", `result: ${JSON.stringify(data)}`);
}, {
year: "2020",
}
);
},
3. Call Cloud Functions without input parameters.
JavaScript:
callWithoutParam:function() {
this._func.wrap("testcodelab-$latest").call((err, data) => {
if (err !== null) {
console.log("Cloud Function", `error: ${JSON.stringify(err)}`);
}
console.log("Cloud Function", `result: ${JSON.stringify(data)}`);
});
},
4. Obtain and set the timeout interval of a function.
JavaScript:
setTime:function() {
this._func.wrap("testcodelab-$latest").setTimeout(100,3);
console.log("Cloud Function", `setTime: ` + 100);
},
getTime:function() {
let currTime = this._func.wrap("testcodelab-$latest").getTimeout();
console.log("Cloud Function", `currTime: ` + currTime);
},
6. Packaging and Testing
In Cocos Creator, go to Project > Build…, package an Android app, and install it to your device. To verify the functions, click the buttons from top to bottom.
If the following information is displayed in JavaScript logs, the integration is successful.
7. Summary
Cloud Functions allows you to keep all functions and related code on the cloud side. You only need to call the wrap.call method to trigger the functions, which reduces the code amount and package size of your APK package.
For more details, please check:
Cloud Functions development guide:
https://developer.huawei.com/consum...connect-Guides/agc-cloudfunction-introduction
Cocos documentation:
https://docs.cocos.com/creator/manual/en/cocos-service/agc-cloudfunc.html

Categories

Resources