外部调用节点
概述
当Rivet从运行@ironclad/rivet-core
或@ironclad/rivet-node
的主机应用程序运行时,您可以在运行图表或创建GraphProcessor时附加"外部函数"。以下外部函数sum
将对其所有参数求和:
import { runGraphInFile } from '@ironclad/rivet-node';
await runGraphInFile({
...etc,
externalFunctions: {
sum: (...args) => {
return {
type: 'number',
value: args.reduce((acc, curr) => acc + curr, 0);
}
}
}
})
然后你可以使用External Call
节点从图中调用这些外部函数。要调用的函数在External Call节点的编辑器中配置,必须与运行图时传递给externalFunctions
的函数名称匹配。
外部函数在许多使用场景中非常有用,它们可以实现诸如:
- 从您的数据库获取数据
- 调用Web API
- 获取关于谁正在运行图表的用户信息
- 其他你能想到的任何功能!
外部函数功能极其强大。它们只能在从宿主应用程序运行Rivet时使用,在Rivet应用程序中运行Rivet时不可用。在Rivet应用程序中运行时,外部函数节点会报错。使用远程调试在Rivet应用程序中运行外部调用节点。
- 输入
- 输出
- 编辑器设置
输入项
标题 | 数据类型 | 描述 | 默认值 | 备注 |
---|---|---|---|---|
Arguments | any or any[] | The arguments to pass into the external call. | (empty array) | To pass in multiple arguments, they must be an array. You can use an Array Node to create an array of any data. |
输出
标题 | 数据类型 | 描述 | 备注 |
---|---|---|---|
结果 | (任意) | 外部调用返回的值。 | 可以是任何数据类型,请确保返回的是您期望的内容! |
Error | string | If the external call errors, will be populated with the error message. | Only enabled if Use Error Output is turned on. If Use Error Output is turned off, the node will error instead. |
编辑器设置
设置 | 描述 | 默认值 | 使用输入切换 | 输入数据类型 |
---|---|---|---|---|
Function Name | The name of the external function as defined in externalFunctions . Must match the function name defined in your code. | (empty string) | Yes | string |
Use Error Output | If enabled, then the External Call node will not fail, but instead any error will appear in the Error output port of the node. If disabled, the entire External Call node will error if the call errors. | False | No | N/A |
示例1:从图表中调用数据库
在这个示例中,我们将创建一个图表,通过调用数据库获取单个用户的元数据。首先,我们将定义进行数据库调用的外部函数:
import { runGraphInFile } from '@ironclad/rivet-node';
const db = {
async getUser(id: string) {
return {
name: 'test user',
};
},
};
await runGraphInFile({
...etc,
externalFunctions: {
getUser: async (userId: string) => {
const user = await db.getUser(userId);
return {
type: 'object',
value: user,
};
},
},
});
然后,在您的图表中,创建一个外部调用节点,并将Function Name
设置为getUser
。创建一个文本节点并将文本设置为用户ID。将文本节点连接到外部调用节点。图表应该如下所示:
运行您的应用程序,并将Remote Debugger连接到它。然后运行图表。您应该在External Call节点中看到从数据库调用返回的对象。
错误处理
如果外部函数出错,那么外部调用节点也会出错。如果你想在图中处理错误,可以启用Use Error Output
设置。这将使外部调用节点不会报错,而是将错误信息传递到Error
输出端口。如果Error
端口有数据,则Result
端口不会运行。你可以使用If Node来检查Error
端口是否有数据,并相应地处理错误。
常见问题
问:在Rivet应用程序中运行Rivet时,可以使用外部函数吗?
不,外部函数仅在从宿主应用程序运行Rivet时可用。连接Remote Debugger到您的宿主应用程序,即可在Rivet应用程序中运行外部函数。
问:从外部函数应该返回什么?
你必须返回一个有效的Data Value并带有有效的Data Type,例如要返回一个字符串:
{
type: 'string',
value: 'hello world',
}
问:我可以从外部函数返回一个Promise吗?
是的,你可以从外部函数返回一个Promise。外部调用节点会等待Promise解析后再继续执行。
问:外部函数与触发事件有何不同?
外部函数是同步的,可以返回数据。触发事件是异步的,不能返回数据。Raise Event节点不会等待事件被处理就继续执行,而External Call节点会等待外部函数返回后才继续执行。