ThingWorx Flow > ThingWorx Flow SDK > ThingWorx Flow SDK 概述
ThingWorx Flow SDK 概述
需要在每个连接器模块中包含 ThingWorx Flow 连接器 SDK,例如 ptc-flow-sdk。运行 init 命令时会生成 package.json 文件,其中已包含此模块。
ThingWorx Flow 服务器使用 flow-sdk 来加载连接器和访问其中附带的“连接”、“操作”、“触发器”和“查找”。
ThingWorx Flow 连接器 SDK 还会提供下列 API 以供连接器使用:
日志记录
连接器内的所有日志记录都必须使用 SDK 提供的日志记录 API 来完成。这有助于有效调试问题。要访问日志记录 API,请在源文件顶部的节点 js 代码中添加以下行:
const logger = require('ptc-flow-sdk').getLogger('module-name')
将上面的模块名称替换为“操作”、“触发器”或“查找”等的名称。
记录器有 4 种方法:debugerrorwarninfo。根据原因选择适当的方法。
日志语句可以记录字符串和 JSON 对象。
CustomFilters
CustomFilters 是一个帮助程序 API,可用于筛选由 JSON、字符串或数字构成的数组。CustomFilters 可用于筛选为操作或触发器提供的输入。使用 customFilters 是一个两步过程。第一步是在输入架构中创建 customFilters 属性,如下所示。这一步是为了让用户在 GUI 中选取运算符和操作数。
"input": {
"type": "object",
"title": "Select Trigger",
"properties": {
"customFilters": {
"type": "array",
"title": "Custom Filters",
"items": {
"type": "object",
"title": "filter",
"properties": {
"input": {
"type": "string",
"title": "Input",
"minLength": 1
},
"operator": {
"type": "string",
"title": "Condition",
"enum": [
"Equals",
"Equals(Number)",
"GreaterThan",
"LessThan",
"Contains",
"DoesNotContains",
"matches",
"isNull",
"isEmpty",
"isNumber",
"isObject",
"isArray",
"isBoolean",
"isDate",
"isUndefined"
]
},
"expected": {
"type": "string",
"title": "Expected",
"minLength": 1
}
}
}
}
}
第二步是使用 CustomFilters API 的 filter 方法。使用 CustomFilters 的片段如下所示:
//add the first line of the code to the top of the node js script
const customFilters = require('ptc-flow-sdk').CustomFilters;
function execute (input, options, output) {
run(input, options, function (err, data) {
if (err || !data) {
return output(err || 'empty')
}
customFilters.filter(input.customFilters, data, output
})
}
在上述片段中,run 方法执行了一些代码,可能是一个会返回数据数组的 http 调用。input.customFilters 是您之前在设计工作流时所选择的筛选条件。output 是使用筛选结果调用的回调函数。
帮助程序
帮助程序对象具有多种实用程序 JavaScript 方法。
toStr(obj) - 用于将任意对象转换为字符串
toISO(str) - 用于将字符串或以毫秒表示的字符串转换为 ISO 格式的字符串。
toNumber(obj) - 用于尝试将字符串转换为数字。
clone() - 用于执行对象的浅层复制
deepClone() - 用于执行对象的深层复制
mix(a,b):组合对象 ab,用于返回同时包含 ab 两种属性的新对象