云函数
callFunction
1. 接口描述
接口功能:执行云函数
接口声明:callFunction<ParaT, ResultT>(callFunctionOptions: ICallFunctionOptions<ParaT>, opts?: ICustomReqOpts): Promise<CallFunctionResult<ResultT>>
2. 输入参数
字段 | 类型 | 必填 | 说明 |
---|---|---|---|
callFunctionOptions | ICallFunctionOptions<ParaT> | 是 | 云函数调用请求参数 |
opts | ICustomReqOpts | 否 | 自定义配置,目前支持 SDK 请求超时时间设置,{timeout: number} |
ICallFunctionOptions<ParaT>
云函数参数:
字段 | 类型 | 必填 | 说明 |
---|---|---|---|
name | string | 是 | 云函数名称 |
data | ParaT | 否 | 云函数参数 |
qualifier | string | 否 | 云函数版本标识:$LATEST (最新版本) 1 2 3 ,缺省时按平台配置流量比例分配流量 |
函数型云托管 额外可以传参数,传入 type:'cloudrun'
参数后,将调用函数型云托管服务
字段 | 类型 | 必填 | 说明 |
---|---|---|---|
type | cloudrun | 否 | 是否调用 基于 云托管的函数型云托管 |
method | string | 否 | HTTP 请求方法 |
path | string | 否 | HTTP 请求路径 |
header | Record<string, string> | 否 | HTTP 请求头 |
data | object | 否 | HTTP 请求体 |
3. 返回结果
Promise<CallFunctionResult<ResultT>>
字段 | 类型 | 必填 | 说明 |
---|---|---|---|
result | ResultT | 否 | 云函数执行结果 |
requestId | string | 否 | 请求序列号,用于错误排查 |
函数执行报错,将通过异常抛出
4. 示例代码
import tcb from "@cloudbase/node-sdk";
const app = tcb.init({
env: "xxx",
});
exports.main = async (event, context) => {
const res = await app.callFunction({
name: "test",
data: { a: 1 },
});
console.log(res); // 打印函数调用结果
const res1 = await app.callFunction(
{
name: "test",
data: { a: 1 },
},
{
timeout: 5000,
}
);
console.log(res1);
};
函数型云托管 示例代码:
import tcb from "@cloudbase/node-sdk";
exports.main = async (event, context) => {
const { httpContext } = context;
const { url, httpMethod } = httpContext;
return `[${httpMethod}][${url}] Hello world!`;
const tcbapp = tcb.init({ context });
const result = await tcbapp.callFunction(
{
name: "helloworld",
// 函数型云托管 参数
type: "cloudrun",
method: "POST",
path: "/abc",
data: {
key1: "test value 1",
key2: "test value 2",
},
},
{
timeout: 5000,
}
);
console.log(result);
};