I'm running into inconsistent behavior when trying to encode my messages. I have the following .proto
files.
BaseMessage.proto
syntax = "proto3";
package mypackage;
message BaseMessage {
string id = 1;
string event_name = 2;
string timestamp = 3;
}
CategoryMessage.proto
syntax = "proto3";
package mypackage;
message CategoryMessage {
string category_id = 1;
}
syntax = "proto3";
package mypackage;
import "BaseMessage.proto";
import "CategoryMessage.proto";
message EventMessage {
BaseMessage base = 1;
CategoryMessage category = 2;
string action = 3;
string name = 4;
}
Then my code looks similar to this:
let protobuf = require("protobufjs");
base = {
id: "test-id",
event_name: "test-event",
timestamp: "20221122T123421"
}
category = {
category_id: "test_category"
}
testEvent = {
action: "do_something",
name: "Bob"
}
run(base,category,testEvent);
async function run(base, category, event){
const rootBase = await protobuf.load("BaseMessage.proto");
const rootCategory = await protobuf.load("CategoryMessage.proto");
const rootEvent = await protobuf.load("EventMessage.proto");
const Base = rootBase.lookupType("mypackage.BaseMessage");
const Category = rootCategory.lookupType("mypackage.CategoryMessage");
const Event = rootEvent.lookupType("mypackage.EventMessage");
const baseBuffer = Base.encode(base).finish();
const categoryBuffer = Category.encode(category).finish();
const eventBuffer = Event.encode(event).finish();
console.log(Base.decode(baseBuffer));
console.log(Category.decode(categoryBuffer));
console.log(Event.decode(eventBuffer));
}
The above code will result in the following output:
BaseMessage { id: 'test-id', timestamp: '20221122T123421' }
CategoryMessage {}
EventMessage { action: 'do_something', name: 'Bob' }
For some reason it's missing event_name
from base
and category_id
from category
for no reason that I can understand.
Has anyone else encountered this before? Is there a reason certain fields don't seem to work properly? Or am I just missing something obvious?
After more exploration I figured out that protobufjs
doesn't support fields with underscores (_
), which is unfortunate.