Reputation: 355
I am looking to encode a map like this in a protobuf:
const newVisMap = new Map<number, IOutput[]>();
The value is an array of objects that all have the same interface (with one optional entry):
interface IOutput {
glyph: string,
color: string,
hex?: string,
order: number
}
My question is how I would go about encoding this map as a field in a protobuf message. Or should I convert the map to another format? This is using the protobuf.js npm module.
Upvotes: 0
Views: 568
Reputation: 8414
There's a lot of detail missing from the question, but I think I can infer that, although the objects all share the same interface, they are in fact of different types where glyph and hex (being strings) suggest that this is where the differences between objects are.
The problem here is that GPB is all about strong types; it's most useful if, when writing a schema, it ends up being the complete definition of the data. The use of string hints that that is going to get parsed in some way, and that the schema isn't telling us how to completely interpret the data.
For example, you have color as string; that could be better as three integers, one for red, green, blue. A color name is ambiguous! Or is it a X hex string from a color?
Also if the information in glyph is not enough to be able to construct an object (perhaps it's referring to class identity, and it is the class constructor knows the parameters needed to create a new object), then you have a separation of information; some in the code, and some in the schema. That might be perfectly OK for yourself, but it might be problematic if this data is ever received by some other system written in a different language; the recipient won't have your constructors!
The best way of doing this would be to have GPB messages in a schema that fully describe each possible object, and then have them contained in an overall oneof
message (which is what you send). That way you're conveying object type, and explicit (and hard to misinterpret) data about the object.
If they're all very similar and generic in content and behaviour, you might be OK having a universal class that can describe all your different object, in which case just describe that class.
It's interesting to consider the import of your comment about stringifying the map and sending that. Stringifying is serilisation, and GPB is another serialisation. The significance is that either you need to go further with your GPB schema (as I suggest above), or not use it at all!
Upvotes: 1