gtfs-realtime-bindings
gtfs-realtime-bindings copied to clipboard
Deserializing feed: missing optional fields return 0 value in node.js
Given a feed that does NOT have an optional field (e.g. vehicle speed), the value returned when getting this value is 0
. So there's no way to differentiate "not included" from an actual value of zero.
const feed = realtime.transit_realtime.FeedMessage.decode(protobuf);
feed.entity.forEach((entity) => {
if (entity.vehicle) {
const speed = entity.vehicle.position.speed; // speed is 0
}
});
This may be similar to #52
@nselikoff Thanks for the report! In Java bindings there is a hasSpeed()
method that you can call to determine if the field has been set, but I'm not as familiar with the Node.js bindings. I'm assuming there isn't an equivalent?
@barbeau good question - just looked and there is not a similar method. However, I found a workaround using realtime.transit_realtime.Position.toObject
:
const feed = realtime.transit_realtime.FeedMessage.decode(protobuf);
feed.entity.forEach((entity) => {
if (entity.vehicle) {
// using `toObject` only adds properties that exist in the protobuf
const position = realtime.transit_realtime.Position.toObject(entity.vehicle.position);
// so speed will be undefined if not included in the protobuf
const speed = position.speed;
// maybe you want it null
// const speed = position.speed || null;
}
});