Skip to content

数据转换

SDK 自动将你的产品数据转换为 TopBridge App 所需的结构化格式。这是schema 驱动的:当你调用 print.execute() 时,SDK 内部自动获取模板 schema,并根据每个字段的 fieldType 应用转换。

不需要手动指定字段类型——SDK 自动处理一切。

WARNING

扁平自动分组写法已移除。 pricecurrencyunit 作为同级键的扁平产品数据格式不再支持。请使用嵌套对象语法点路径语法

工作原理

print.execute({ template, printer, products })
  ├─ 1. 自动获取模板 schema(自动完成,无需手动调用)
  ├─ 2. 按 fieldType 分类字段
  │     ├─ Widget 字段: text, textfield, price, weight, barcode, qrcode
  │     ├─ Protocol 字段: integer
  │     └─ Layout 字段: line (跳过)
  ├─ 3. 转换每个产品的数据
  └─ 4. 向 TopBridge App 发送打印指令

print.execute() 自动完成整个流程——你只需提供正确字段名的产品数据。

转换规则

fieldType输入输出说明
text'Apple\n有机水果''Apple'截取第一行 + 警告
textfield'第一行\n第二行''第一行\n第二行'保留换行,过滤 =/=@
price{ value: 3.99 }{ value: 3.99 }标量自动包装
price{ value: 3.99, currency: '$' }{ value: 3.99, currency: '$' }嵌套对象保留
weight{ value: 0.5 }{ value: 0.5 }标量自动包装
barcode12345'12345'强制转字符串
barcodenull''null → 空字符串
qrcode'https://...''https://...'强制转字符串
integer42'42'强制转字符串
line(任意)(跳过)无数据绑定

产品数据格式

Products 是 JSON 对象。结构化字段使用嵌套对象或点路径语法:

typescript
const products = [
  { name: 'Apple', price: { value: 3.99, currency: '$', unit: '/kg' }, barcode: 12345, copies: 2 },
  { name: 'Banana', price: { value: 1.99, currency: '$' }, copies: 1 },
]

嵌套对象语法

对于结构化字段(price、weight),使用嵌套对象:

typescript
const products = [
  { name: 'Apple', price: { value: 3.99, currency: '$', unit: '/kg' }, copies: 2 },
]

点路径语法

对于结构化字段(price、weight),可以使用点路径键:

typescript
const products = [
  { name: 'Apple', 'price.value': 3.99, 'price.currency': '$', 'price.unit': '/kg' },
]

两种语法产生完全相同的输出。

copies 规则

copies 是保留关键字,控制打印份数:

规则说明
范围[1, 9999],超出自动截断
默认值1(等于默认值时输出中省略)
无效值null、NaN、非数字 → 回退到 1
小数自动取整(Math.round()
typescript
// copies: 2 → 输出包含 copies: 2
// copies: 1 → 输出省略 copies(默认值)
// copies: 0 → 输出 copies: 1(截断)
// copies: 10000 → 输出 copies: 9999(截断)
// copies: null → 输出省略 copies(默认 1)

文本换行处理

TSPL 协议按行解析指令。text 类型字段值中的换行符(\n\r\r\n)会破坏 TSPL 指令结构。

text 字段值包含换行符时,SDK:

  1. 截取第一行
  2. 在响应中添加警告:{ code: 'DATA_FORMAT', reason: 'newline_truncated', message: '...' }

这仅适用于 schema 中 fieldType 为 text 的字段。textfield 会保留换行符。

警告类型

PrintResponse.warnings 可能包含来自两个来源的警告:

codereason来源说明
DATA_FORMATnewline_truncatedSDK 客户端text 字段包含换行符,已自动截取第一行
DPI_MISMATCHTopBridge App打印机 DPI 与模板设计 DPI 不匹配

两者合并到响应的 warnings[] 数组中。这些是非致命警告——打印任务仍会正常执行。

公式注入防护

对于 textfield 类型字段,SDK 自动从输入值中剥离公式注入前缀(==@。这是内置的安全防护——开发者无需手动清洗数据。

输入:  '=SUM(A1:A10)'   →   输出: 'SUM(A1:A10)'
输入:  '=@cmd'           →   输出: 'cmd'

已废弃的参数

WARNING

fieldTypesrawProducts 参数已被移除。传入会抛出 TopBridgeValidationError

typescript
// ❌ 旧写法(会报错)
await client.print.execute({
  template: 'PRICE_LABEL',
  printer: 'TSC DA220',
  products: [{ name: 'Apple', price: 3.99 }],
  fieldTypes: { price: 'price' },  // 已移除
})

// ✅ 新写法(正确)
await client.print.execute({
  template: 'PRICE_LABEL',
  printer: 'TSC DA220',
  products: [{ name: 'Apple', price: { value: 3.99, currency: '$', unit: '/kg' } }],
})