使用函数服务的 SDK 可以更加便捷地执行创建函数、上传代码和管理触发器等操作。本文介绍 Node.js SDK 的使用案例。
目前还没有正式支持 Node.js SDK。
如果需要使用 Node.js SDK,可以通过@volcengine/vcloud-core
实现鉴权逻辑后请求 OpenAPI。
npm install @volcengine/vcloud-core npm install axios
const { Signer } = require("@volcengine/vcloud-core"); const axios = require("axios"); const version = "2024-06-06"; // API Version const serviceName = "vefaas"; // ServiceName const apiHost = "open.volcengineapi.com"; // OpenAPI host class CustomClient { constructor(options) { this.instance = this.axiosRequest(options); } axiosRequest(options) { const { region, accessKey, secretKey, host, headers, serviceName, version, } = options; const baseURL = "http://" + host; const instance = axios.create({ baseURL: baseURL, method: "POST", params: { Version: version }, headers, }); instance.interceptors.request.use((config) => { const requestInfo = { region: region, method: config.method || "POST", pathname: "/", params: config.params || {}, body: config.data, headers: config.headers, }; const signer = new Signer(requestInfo, serviceName); signer.addAuthorization( { accessKey, secretKey, }, new Date() ); return config; }); instance.interceptors.response.use( (config) => { console.log(config.data); return config.data; }, (err) => { console.log( "Response Error: ", err?.response?.data?.ResponseMetadata?.Error?.Message || err?.response?.data ); const errorMessage = err?.response?.data?.ResponseMetadata?.Error?.Message; return Promise.reject(errorMessage); } ); return instance; } async CreateFunction(params) { return await this.instance.request({ data: params, params: { Action: "CreateFunction" }, }); } } const client = new CustomClient({ region: "cn-beijing", accessKey: "yourAccessKeyId", secretKey: "yourAccessKeySecret", host: apiHost, serviceName, version, }); client .CreateFunction({ Name: "micro-service-doctest", Runtime: "native/v1", VpcConfig: { EnableVpc: true, VpcId: "vpc-id", SubnetIds: ["subnet-id"], SecurityGroupIds: ["sg-id"], }, Command: "./run.sh", CpuStrategy: "always", }) .then((res) => { console.log(res, "response"); }) .catch((err) => { console.error(err, "error"); });
请根据业务真实情况配置代码参数,可参考文档CreateFunction,下表只介绍创建微服务应用时的特殊配置。
参数 | 说明 |
---|---|
Runtime | 设置函数的 Runtime 运行时。 |
CpuStrategy | CPU 分配方式。微服务应用默认为始终分配 CPU,取值为 |
Command | 程序的启动命令。 |
通过 SDK 创建函数后,您可以登录函数服务控制台查看是否成功创建函数,微服务应用的CPU 分配模式固定为始终分配。