Converting protobuf.js Types to custom formats

Viewed 226

In my protobuf schema, I have a type that contains binary data (already defined in an existing schema, I can't change this):

// message BinaryKey { bytes data = 1; }

let BinaryKey = new Type('BinaryKey')
BinaryKey.add(new Field('data', 1, 'bytes'))

In my application JSON, I have a human readable string format of this field/type and would like to use this string for my field that is passed to encode(). What is the correct way to have encode() and decode() use custom conversion functions between string and binary format?

A full example of my code (using protobuf.js reflection):

let BinaryKey = new Type('BinaryKey')
BinaryKey.add(new Field('data', 1, 'bytes'))

let Message = new Type('CustomMessage')
Message.add(new Field('balance', 1, 'uint32'))
Message.add(BinaryKey)
Message.add(new Field('bin_key', 2, 'BinaryKey'))

let object = { balance: 100, bin_key: '<String representation>' }; // <-- *** pass in the data as a string to be converted
Message.encode(object).finish();

I would need to specify conversion functions between my string format and the binary field of the schema, but don't know how to add these to my Type (BinaryKey)

0 Answers
Related