user906573
user906573

Reputation: 733

Trying to set protobuf Map entries in Typescript

I have the following protobuf message:

syntax = "proto3";

message MyMessage {
  string id = 1;
  map<string, Any> attributeChanges = 2;
}

In typescript I am trying to set the map entries of the protobuf message based on a typescript Map that looks like this.

type Nullable<T> = T | undefined | null;

export interface IAuditChanges {
  currentValue: Nullable<string>;
  previousValue: Nullable<string>;
  fields?: Map<string, IAuditChanges>
}

I try to loop through the entries in the map object and setting the map entries this way.

var attributesMap = message.getAttributechangesMap();
for (let key of Array.from(mappedChanges.keys())) {
  const mapEntry: any = mappedChanges.get(key);
  attributesMap.set(key, mapEntry);
}

I get the error " TypeError: b.toArray is not a function." Any idea how I can cast / serialize / pack each typescript map entry so that I set it in protobuf? I have looked in a few places for examples without luck.

https://developers.google.com/protocol-buffers/docs/proto3#any https://developers.google.com/protocol-buffers/docs/proto3#maps

Thank you.

Upvotes: 0

Views: 1737

Answers (1)

Timo Stamm
Timo Stamm

Reputation: 750

Protobuf Any is very different from TypeScript any. TypeScript any allows any possible JavaScript value.

Protobuf Any on the other hand is a message with exactly two fields:

  1. value: a protobuf message, encoded in binary format

  2. type_url: an identifier for the type of the protobuf message

This means you can't just put anything in an Any field. It must be a protobuf message, packed into a protobuf Any.

The JavaScript reference actually has an example: https://developers.google.com/protocol-buffers/docs/reference/javascript-generated#any

I recommend to write a protobuf message for "IAuditChanges". You most likely won't need Any at all.

Upvotes: 1

Related Questions