簡體   English   中英

如何使用包含可選值的 avro 模式序列化 js object

[英]how to serialize js object with avro schema that contains optional values

我沒有設法用 avro 模式序列化一個簡單的 js object,我不明白為什么。 問題從聯合類型 ["null", "float"] 開始。 它在值為 null 時有效,但在它是數字時無效。

我怎樣才能讓它工作?

圖式

{
  "type": "record",
  "name": "incoming_telemetry",
  "doc": "Telemetry message from herby device",
  "fields": [
    {"name": "deviceId", "type": "string"},
    {"name": "timestamp", "type": "string"},
    {"name": "waterTableRange", "type": ["null", "float"]},
    {"name": "batteryCapacity", "type": ["null", "float"]},
    {"name": "batteryCurrent", "type": ["null", "float"]},
    {"name": "solarVoltage", "type": ["null", "float"]},
    {"name": "batteryVoltage", "type": ["null", "float"]},
    {"name": "temperature", "type": ["null", "float"]},
    {"name": "wifiStrength", "type": ["null", "float"]},
    {"name": "flowRate", "type": ["null", "float"]},
    {"name": "dummy", "type": ["null", "float"]}
  ]
}

腳本

const avro = require('avro-js');
const schema = avro.parse('publishToAnalytics/incoming_telemetry_v1.0.avsc')
const data = {
    deviceId: 'test',
    timestamp: new Date().toDateString(),
    waterTableRange: 1.1,
    batteryCapacity: 2.2,
    batteryCurrent: 3.3,
    solarVoltage: 4.4,
    batteryVoltage: 5.5,
    temperature: 6.6,
    wifiStrength: 7.7,
    flowRate: 8.8,
};
const dataBuffer = schema.toBuffer(data) 

錯誤

Uncaught Error Error: invalid ["null","float"]: 1.1
    at throwInvalidError (/home/marc/coding/boum/iot/node_modules/avro-js/lib/schemas.js:2204:9)
    at UnionType._write (/home/marc/coding/boum/iot/node_modules/avro-js/lib/schemas.js:803:7)
    at writePet (<eval>/VM46947624:5:82)
    at Type.toBuffer (/home/marc/coding/boum/iot/node_modules/avro-js/lib/schemas.js:259:8)
    at <anonymous> (/home/marc/coding/boum/iot/publishToAnalytics/publishToAnalytics.js:16:18)
    at Module._compile (internal/modules/cjs/loader:1101:14)
    at Module._extensions..js (internal/modules/cjs/loader:1153:10)
    at Module.load (internal/modules/cjs/loader:981:32)
    at Module._load (internal/modules/cjs/loader:822:12)
    at executeUserEntryPoint (internal/modules/run_main:81:12)
    at <anonymous> (internal/main/run_main_module:17:47)

使用庫avsc而不是avro-js解決了這個問題。 無需更改代碼的 rest。

const avro = require('avsc');

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM