Skip to main content

Quick Start

A cloud function is essentially a piece of code. Here, using Node.js as an example, we introduce how to create a cloud function.

Node.js services typically require an entry file index.js. If you utilize npm packages, a package.json file is also needed to describe dependencies.

Therefore, the most basic Node.js service directory structure is as follows:

└── helloWorld
├── index.js
└── package.json

Creating a Cloud Function

You can create a cloud function in the following three ways. Please choose the appropriate method based on your development environment:

Go to TCB/cloud function, click the Create New Cloud Function button.

  1. Choose a suitable template. If none is suitable, you can create from scratch.
  2. Select the runtime environment as Nodejs 18.15 (other versions are also selectable)
  3. Fill in the function name
  4. Click the Start Creation button

After the creation is completed, go to the cloud function where you can see a default index.js file.

  1. Click Save and Install Dependencies below to complete the deployment of the cloud function.

Invoking Cloud Functions

There are mainly the following methods to invoke cloud functions:

  • Use the TCB SDK
  • Use the HTTP access service
  • Use the HTTP API
  • Use triggers

Using the SDK to Invoke Cloud Functions

wx.cloud
.callFunction({
// cloud function name
name: 'hello_world',
// Parameters passed to the cloud function
data: {
a: 1,
},
})
.then((res) => {
console.log(res); // Hello World!
})
.catch(console.error);

Accessing and Invoking Cloud Functions via HTTP

You can choose to create an HTTP service to access cloud functions and then invoke cloud functions via HTTP.

There are two operation methods:

TCB console

  1. Go to TCB/HTTP Access Service

  2. Create a new "domain association resource":

    • Select cloud function as the associated resource, hello_world
    • Select the default domain, or choose your custom domain
    • Enter the trigger path, here enter /hello

  1. Click OK, wait for 3-5 minutes, and the HTTP service will be created.

  1. The HTTP service address is default domain + trigger path. You can also choose to bind resources using a custom domain.

CLI tool

For details, see HTTP Access Service

Run the following command to create an HTTP service route with the path /hello pointing to the hello_world cloud function:

tcb service create -p hello -f hello_world -e <env-id>

Then you can go to TCB/HTTP Access Service to view the created HTTP service.

Using HTTP API to Invoke Cloud Function

After creating a cloud function, you can invoke it from any client via HTTP API without the need for an SDK.

For details, see HTTP API Invoking Cloud Functions. Accessing the HTTP API requires an ACCESS_TOKEN.

curl -L 'https://your-envId.api.tcloudbasegateway.com/v1/functions/:name' \
-H 'Content-Type: application/json' \
-H 'Accept: application/json' \
-H 'Authorization: Bearer <ACCESS_TOKEN>' \
-d '{}'