protobufjs encode a wrapper message which includes an inner field with type google.protobuf.Any

242 Views Asked by At

I am using protobufjs library in Nodejs to send a message to a kafka topic and read the message from a java consumer.

Following are the protobuf definition. The Inner message should be packed in the Wrapper message field.

message Wrapper {
  google.protobuf.Any message = 1;
}

message Inner {
  string field1 = 1;
}

I used the following three methods to encode the message but when deserializing i get error "Type of the Any message does not match the given class." in the java consumer.

const rootWrapper = await protobuf.load('wrapper.proto');
const Wrapper = rootWrapper.lookupType('Wrapper');
const rootInner = await protobuf.load('inner.proto');
const Inner = rootInner.lookupType('Inner');
const rootAnyProto = await protobuf.load('node_modules/google-proto-files/google/protobuf/any.proto');
const Any = rootAnyProto.lookupType('google.protobuf.Any');

Method 1

const innerMsg = { field1 : 'value1'}
const wrapper = { message: innerMsg }

const encodedWrapper = Wrapper.encode(wrapper).finish()

Method 2

const innerMsg = { field1 : 'value1'}
const innerMsgEncoded = Inner.encode(innerMsg).finish()
const wrapper = { message: innerMsgEncoded }

const encodedWrapper = Wrapper.encode(wrapper).finish()

Method 3

const innerMsg = { field1 : 'value1'}
const innerMsgEncoded = Any.encode(innerMsg).finish()
const wrapper = { message: innerMsgEncoded }

const encodedWrapper = Wrapper.encode(wrapper).finish()

Anyone can help on the correct way to encode an protobuf message with an inner message?

1

There are 1 best solutions below

0
On

After many tries i resolved my issue in the following manner.

const innerMsg = { field1 : 'value1'}
const innerMsgEncoded = Any.encode(innerMsg).finish()
const any = Any.create({ type_url : 'type.googleapis.com/Inner', value : innerMsgEncoded });

const wrapper = { message: any}
const encodedWrapper = Wrapper.encode(wrapper).finish()