# Cloud function/cloud object operation mode introduction

During development, cloud functions or cloud objects can be run in the local environment provided by HBuilderX, or connected to the uniCloud cloud on the existing network.

Note: The local running environment only includes cloud functions and DB Schema, and the data content must be in the cloud. Because the local runtime environment does not have MongoDB.

Cloud functions/cloud objects can run directly in the local or cloud cloud function environment, or the uni-app client can connect to the cloud function to trigger the local or cloud running environment for joint debugging.

Cloud objects are a type of cloud functions, so when many interface menus or documents do not individually emphasize, "cloud functions" will include "cloud objects".

So to sum up, cloud functions have 4 operating modes:

  1. Run locally
  2. Upload to the cloud and run (cloud objects do not support this mode)
  3. The client connects to the local cloud function to run
  4. The client connects to the cloud to run the cloud function

Cloud functions/cloud objects can be run via menu or shortcut keys.

  1. Right-click menu: Right-click the cloud function directory in the project manager, and select "Run cloud function locally", "Upload and run cloud function" in the pop-up menu
  1. Toolbar: When the editor opens a cloud function, click the Run button on the toolbar, and the drop-down menu also includes "Run cloud function locally", "Upload and run cloud function"
  2. Shortcut key: When the editor opens the cloud function, press the [Ctrl+r] shortcut key to activate the above run menu.

If the local running plugin is not installed, follow the prompts to install it. HBuilderX 2.8.1+ is required to run cloud functions locally

After running, the cloud function console will be opened, and you can see the running results and log output in the console.

# Run cloud functions locally

Supported since HBuilderX 2.8.1

Run cloud functions or cloud objects directly in the node environment of HBuilderX's uniCloud local running plugin.

How to use

In the cloud function editor, press Ctrl+r to run the shortcut key (or click Run on the toolbar) to see several menus for running cloud functions. Ctrl+r and press Enter or select 0 to execute the local operation, you can immediately see the operation results and log output in the console. As shown below:

Cloud functions print console.log to see the log.

When running a cloud function, if you need to pass parameters to the cloud function but do not want to start the client, you can pass the test parameters by configuring a json file.

Right-click on the directory corresponding to the cloud function to configure the running test parameters, as shown in the figure below. After selection, a file in the form of ${function name}.param.json will be generated. The content of this file will be uploaded and run in the cloud function and When running the cloud function locally, it is passed into the cloud function as a parameter. For detailed usage, please refer to: Configure running test parameters

# Upload and run cloud functions

Right-click the cloud function directory in the project manager, and select "Upload and run cloud function" from the pop-up menu. Alternatively, you can open the file in this directory and then use the shortcut key Ctrl+r to select "Upload and Run Cloud Function" in the pop-up menu.

For cloud functions, the configured running test parameters are automatically included when uploading and running. Please refer to: Configure run test parameters

# Client joint debugging cloud function

Supported since HBuilderX 3.0.0

Running a uni-app project with uniCloud starts the uniCloud console in addition to the client console.

You can switch whether to connect to a local cloud function or a cloud cloud function in the upper right corner of the client console, as shown in the following figure

The uniCloud console log is as follows:

At this point, you can see both the client log and the cloud function log, which is very convenient for joint debugging.

Note: It is necessary to pay attention to the development of small programs. During development, the domain name verification should be turned off to establish a connection with the local debugging service. Do not use the run menu of HBuilderX to publish the trial version and online version. The trial version and the final release version should be compiled in release mode.

Configuration save

After switching between the cloud function and the local cloud function, a launch.json file will be created in the .hbuilderx directory under the project.

A typical launch.json looks like this (no need to manually create this file)

{
    "version": "0.0.1",
    "configurations": [
      {
        "app-plus": {
          "launchtype" : "local" // app平台连接本地云函数
        },
        "default": {
          "launchtype" : "remote" // 未配置的平台连接云端云函数
        },
        "h5": {
          "launchtype" : "remote" // h5平台连接云端云函数
        },
        "provider": "aliyun", // 如果项目仅关联一个服务空间无需此参数,支持的值:aliyun,tcb
        "type": "uniCloud", // 标识此项配置为uniCloud配置,必填
        "systemLog": false // 设置为false之后关闭云函数控制台的系统日志(主要是云函数入参、返回值,错误信息不会关闭)
      }
    ]
}

# HBuilderX local uniCloud operating environment introduction

HBuilderX 2.8.1+ supports uniCloud to run plugins locally.

Whether the cloud function runs directly locally or the client connects to the local cloud function, the uniCloud local running plugin is used.

The difference between the local operating environment and the current uniCloud network:

# 本地环境只有node运行环境

That is, cloud functions and DB Schema can be used locally, but there is no MongoDB, no redis, and no cloud storage locally, and the data content is still stored in the uniCloud live network service space. The database index also takes effect in the cloud.

# node版本差异

The nodejs version running locally is node12.

The nodejs version of the service space can be selected from 8 or 12. If you use the nodejs api, it is recommended to test the compatibility after deploying to the cloud after local testing. If you only use the uniCloud api, there is no need to worry about compatibility.

# 本地环境的云函数没有超时限制

Cloud function timeout and running memory configuration will not take effect during local debugging.

# 扩展库功能差异

HBuilderX自带的uniCloud环境内扩展库的能力仅支持到此HBuilderX发布时,需要更新HBuilderX才可以使用扩展库后续增加的能力

# return 策略差异

See details

# 公用模块使用注意

  • Before HBuilderX 3.0.0, you need to execute npm install ../common/xxx in the cloud function to install the common module. For details, please refer to Cloud Function Common Module
  • If you use HBuilderX 3.0.0 and above, you can directly right-click in the cloud function directory and select "Manage Common Module Dependencies" to import public modules
  • This cloud function cannot be run locally if encrypted public modules are used
  • When the HBuilderX 3.0.0 version runs the uniCloud project, the uniCloud local debugging plugin will automatically install cloud function dependencies (including public modules and other dependencies in package.json)

# Time zone issues

The time zone used by cloud functions in the uniCloud cloud is utc+0, the local time is used when running locally, and China is generally +8. There is no difference between the two when using "timestamp", but if you want to get the year, month, day, and hour, pay attention to the difference in time zones.

The following methods can obtain the year, month, day, and hour of the specified time zone, you can refer to

// Get the offset Date object, for example, when utc+x, the offset will pass x
function getOffsetDate (offset) {
  return new Date(
    Date.now() + (new Date().getTimezoneOffset() + (offset || 0) * 60) * 60000
  )
}

// Get the hours in utc+8
const hour = getOffsetDate(8).getHours()

// There is no need to use this method to get the timestamp. The utc+0 timestamp is consistent with the utc+8 timestamp

It is recommended to use the <uni-dateformat> component to format the display date, details

# Call other cloud functions within the cloud function

When the version before HBuilderX 3.4.0 "run the cloud function locally", the callFunction in the cloud function will call the cloud function deployed on the cloud, and the version of HBuilderX 3.4.0 and later will call the local cloud function

"When the client connects to the local cloud function" callFunction in the cloud function will call the local cloud function

# Data and Storage

It is important to note that cloud functions are still connected cloud databases and storages when running locally

Cloud function uploading files to cloud storage is only supported by Tencent Cloud. Of course, you can also upload files directly on the front end, which is supported by Alibaba Cloud and Tencent Cloud.

# Plugin market encryption plugin

The encrypted cloud functions or public modules sold in the plug-in market cannot be run locally until the source code is purchased. The local runtime automatically requests cloud functions that have been deployed in the cloud. Note the console output.

When sending a clientDB request, if an encrypted action (sold in the plugin market) is used, the current request will use the cloud-deployed resources instead of local resources (including schema, validateFunction, and action). Please pay attention to the console output.

# File system

Cloud functions run in a read-only file system in the cloud (only /tmp directory can write files), and there are no such restrictions when running locally. To write files when running in the cloud, please operate in the /tmp directory

# Other Considerations

  • Although cloud functions, database schema, and validate functions are local, cloud storage, database data and indexes are still in the cloud. That is, the development machine cannot be completely developed offline. It's just that the code can be written locally, and joint debugging can be done without uploading.
  • Please remember to upload the local schema, validatefunction, action when connecting to the online environment
  • Switch between cloud and local without re-running the client
  • Different platforms can have different configurations. But the same platform, such as Android and iOS are both app-plus, they correspond to the same configuration, or two Android phones can only have one configuration
  • Before sending a cloud function request, the client will send a request to the local debugging service, and the local service will notify the client whether to access the local cloud function or the cloud cloud function according to the current user selection.
  • 客户端连接本地云函数时,云函数内的callFunction也会调用本地云函数。除非目标云函数是插件市场售卖的加密云函数,此时不会调用本地,仍会调用云端
  • 如果项目内关联了两个服务空间,需要在.hbuilderx/launch.json内配置provider参数指定哪个服务空间使用本地调试,注意支持的值为:aliyun,tcb
  • When all clients running in the current project stop running, the debugging service for this project will be closed, and the clients that have already run on the mobile phone will not be able to connect to the local cloud function
  • In the network panel on the h5 side, you will see some requests for Request Method: OPTION. These are cross-domain preflight requests and can be ignored. Please refer to: HTTP's OPTIONS method
  • The scene of using Tencent Cloud custom login is not supported locally
  • If you want to use the local cloud function for debugging when developing the applet, please enable the ignore security domain name verification of the applet
  • The Mini Program trial version cannot connect to local services. If you publish the Mini Program trial version, be sure to use the release mode
  • If the local debugging service cannot be accessed after switching the computer network while using HBuilderX, you need to restart HBuilderX once

# Configure running test parameters when running cloud functions

In the upload and run menu or right-click menu of the cloud function, there is the function of configure running test parameters.

You can open a json and configure the running parameters. After the json is configured, the json will be processed as the upstream parameter of the cloud function call when running the cloud function, and the parameters can be received in the cloud function.

Right-click in the cloud function directory to run the cloud function, or in the cloud function editor, press Ctrl+r to run the shortcut key, or click Run on the toolbar

At this time, the cloud function operation will carry the configured operation parameters.

# Mock client type

If you need to simulate the client type, you can add the clientInfo field to the running parameters. For a complete list of fields, see the description below.

{
  "otherParam": "***",
  "clientInfo":{
    // Versions before HBuilderX 3.5.1 need to pass all uppercase parameters to use context.OS, context.LOCALE, etc. in the context
    "OS": "ios", // 系统类型 ios、android
    "PLATFORM": "web", // 客户端类型 app、web、mp-weixin、mp-alipay等
    "DEVICEID": "", // 设备id
    "APPID": "", // 应用DCloud AppId
    "LOCALE: "", // 客户端语言
    // HBuilderX 3.5.1 and later versions do not need to pass in uppercase parameters. The above parameters are written as follows
    "osName": "ios", // 系统类型 ios、android
    "uniPlatform": "web", // 客户端类型 app、web、mp-weixin、mp-alipay等
    "deviceId": "", // 设备id
    "appId": "", // 应用DCloud AppId
    "locale": "", // 客户端语言
    // HBuilderX 3.5.1 and later also allow mocking of call source (context.SOURCE), client ip (context.CLIENTIP), client ua (context.CLIENTUA)
    "source": "client", // 调用来源,不传时默认为 client
    "clientIP": "127.0.0.1", // 客户端ip,不传时默认为 127.0.0.1
    "ua": "xx MicroMessenger/xxx" // 客户端ua,不传时默认为 HBuilderX
    // ...additional client information
  }
}

Notice

  • In a non-local operating environment, the client getSystemInfoSync will also obtain the ua parameter and upload it to the cloud function, but the cloud function will obtain the ua from the http request header instead of the ua in the clientInfo

# Enter uniIdToken

When the client calls the cloud function, the uniIdToken is automatically added to the data. When using the configuration parameters to run, it can also be passed in the parameters.

{
  "otherParam": "***",
  "clientInfo":{},
  "uniIdToken": "xxxx"
}

# When running the cloud object, pass the configuration running test parameters

Added in HBuilderX 3.5.6

When right-clicking on a cloud object and selecting Run - Local Cloud Object or Debug Run - Local Cloud Object, the run parameter file ${objName}.param.js will be automatically created, which can be configured in the following format parameters, you can run it again after the configuration is complete.

Where const clientInfo = {xxx} is the simulated client information. For a complete list of clientInfo, please refer to: getClientInfo

login('xxx', 'xxx') is used to specify the method name and parameters of the call.

const clientInfo = { // 模拟clientInfo
  uniPlatform: 'web',
  source: 'client', // 调用来源,不传时默认为 client
  clientIP: '127.0.0.1', // 客户端ip,不传时默认为 127.0.0.1
  userAgent: 'xx MicroMessenger/xxx', // 客户端ua,不传时默认为 HBuilderX
  uniIdToken: 'xxx'
}
login('name-demo', 'password-demo') // 调用login方法传入参数'name-demo'和'password-demo'

Notice

  • This file is not an executable js file, it is only used to configure parameters, so variables cannot be defined in the file and used
  • If there are multiple methods, the parameter configuration runtime will use the first one

# Breakpoint debugging cloud function

From HBuilderX 3.2.10, running cloud functions locally and connecting clients to local cloud functions support breakpoint debugging

The way to enable breakpoint debugging is shown in the figure below. After the uniCloud local operating environment is started, select Enable breakpoint debugging in the upper right corner of the uniCloud console.

After the debugging is enabled, the debugging interface will appear, as shown in the following figure. Similar to the browser's debugging function, please refer to: [JavaScript Debugger](https://developer.mozilla.org/zh-CN/docs/Learn/Common_questions/What_are_browser_developer_tools#javascript%E8%B0%83%E8% AF%95%E5%99%A8)

Double-click at the line number of the editor interface of the debug file to insert a breakpoint, or right-click to select more operations (add/delete/disable breakpoints)

To switch back to the project view from the debug interface, click the button at the bottom of the project manager to switch

The uni-app front end also supports debug debugging, be careful not to confuse it.

There is a breakpoint step button above the debug panel, and the shortcut key can be seen by hovering the mouse over it. Single-step debugging is possible. The usage tutorial of the debug panel is the same as the client-side debugging, see details

# Cloud Log

The published cloud functions also have logs under uniCloud web console -> cloud functions.

Logs printed through the console api will be recorded in the cloud.

# Ali Cloud

Alibaba Cloud cloud function logs are kept for up to 7 days

# Tencent Cloud

腾讯云日志服务为套餐外单独计费项。如果你购买了包月套餐,在使用日志服务时会产生额外费用(日志服务为按量计费,从余额扣除)。为避免因日志服务欠费引发其他按量计费资源不可使用,目前新建腾讯云服务空间默认关闭了日志服务(从老的套餐升级到新计费套餐时默认开启),可在 uniCloud web控制台 -> 云函数 -> 日志中开启。

此外日志服务开启的状态下,腾讯云可以设置日志保存时长。