构建 JavaScript 函数
对 JavaScript 函数的剖析,涵盖 HTTP 端点和作业形状、类型化合同、响应帮助程序、错误处理和日志记录。
每个函数都是一个默认导出 defineFunction(...) 对象的模块。CLI 通过 functions 中的 uipath.json 映射发现它。
import { defineFunction, defineSchema } from "@uipath/coded-functions-js-sdk";
export default defineFunction({
name: "process-order",
input: defineSchema<Input>(),
output: defineSchema<Output>(),
handler: async (input, ctx) => { /* ... */ },
});
import { defineFunction, defineSchema } from "@uipath/coded-functions-js-sdk";
export default defineFunction({
name: "process-order",
input: defineSchema<Input>(),
output: defineSchema<Output>(),
handler: async (input, ctx) => { /* ... */ },
});
两种形状
单个字段对决定如何调用函数。
| 图形 | 声明 | 调用者 |
|---|---|---|
| HTTP 端点 | method 和 path 已设置。 | 应用或任何 HTTP 客户端,通过函数的触发器 URL |
| 作业 | method 并省略 path | Maestro 服务任务、运行作业活动、Orchestrator API 或作业触发器 |
这两种形状的打包和部署方式相同。HTTP 函数是编码应用程序的支持;作业功能是更大范围自动化中的步骤。对于第一个触发器,请参阅HTTP 触发器和路由,对于第二个触发器,请参阅调用函数。
合同类型
defineSchema<T>() 将 TypeScript 接口转换为 JSON 架构,驱动在每个调用界面上绑定变量。界面是单一事实来源 — 它指定处理程序并声明合约:
interface CreateOrderInput {
/** Customer reference. */
customerId: string;
/** @default 1 */
quantity?: number;
}
interface CreateOrderInput {
/** Customer reference. */
customerId: string;
/** @default 1 */
quantity?: number;
}
可选属性在架构中将变为可选,并且 JSDoc @default 标签将保留默认值。在 JavaScript 项目中,请传递 JSON 架构对象文本来代替 defineSchema<T>()。
架构是从源中提取的,而不会运行它,因此将它们编写为文本。可以从提取的架构中删除通过变量引用的值(数字绑定或共享架构对象),使函数没有可绑定的合约。
声明 output 是可选项。如果存在,则系统会在处理程序的返回值离开函数之前,对其进行验证。
返回结果
返回一个纯对象,以向 200 发送将该对象作为正文:
handler: async (input) => ({ orderId: input.customerId, processed: true }),
handler: async (input) => ({ orderId: input.customerId, processed: true }),
对于其他任何内容,请返回响应对象或使用帮助程序:
import { ok, created, notFound } from "@uipath/coded-functions-js-sdk";
return created({ id: "new-id" }); // 201
return notFound("No such order"); // 404
return { status: 202, body: { queued: true } };
import { ok, created, notFound } from "@uipath/coded-functions-js-sdk";
return created({ id: "new-id" }); // 201
return notFound("No such order"); // 404
return { status: 202, body: { queued: true } };
由于 { status, body } 是响应形状,因此您自己保存数字的名为 status 的输出字段将读取为状态代码。声明的状态将使用空正文发送,其余有效负载将被丢弃,不会出现错误。为字段命名其他名称,例如 httpStatus。
错误
引发 FunctionError 失败,并显示特定状态和消息:
import { FunctionError } from "@uipath/coded-functions-js-sdk";
if (!input.customerId) {
throw new FunctionError("customerId is required", 400);
}
import { FunctionError } from "@uipath/coded-functions-js-sdk";
if (!input.customerId) {
throw new FunctionError("customerId is required", 400);
}
未捕获的错误将变为 500。当函数作为作业运行时,引发的错误会使作业发生故障,并且消息会到达作业结果。
日志记录
使用 SDK 记录器,将输出归因于运行,并到达 Orchestrator 作业日志:
import { logger } from "@uipath/coded-functions-js-sdk";
logger.info(`Processed order ${input.orderId}`);
import { logger } from "@uipath/coded-functions-js-sdk";
logger.info(`Processed order ${input.orderId}`);
console.* 输出不会转发。绝不可记录密码值。
后续步骤
- HTTP 触发器和路由
- 函数上下文— 身份、平台坐标和请求数据。
defineFunction参考— 每个字段及其默认值。