protobuf-javascript icon indicating copy to clipboard operation
protobuf-javascript copied to clipboard

[JS] Add `fromObject` method to take an AsObject type and return a T.

Open alexandros-megas opened this issue 2 years ago • 5 comments

What language does this apply to? JS/TS

Describe the problem you are trying to solve. In JS, many different libraries expect to work with dictionaries, basically Record<A, B> or lists of these, to do things like state management in single page apps, list operations like find, slice, zip, etc. and more. Having the ability to freely move between a Message and a JSON object would make it MUCH easier to interoperate with different tools.

Currently, my message types get compiled to something like the following:

export class Polygon extends jspb.Message {
  // getters and setters here

  serializeBinary(): Uint8Array;
  toObject(includeInstance?: boolean): Polygon.AsObject;
  static toObject(includeInstance: boolean, msg: Polygon): Polygon.AsObject;
  static serializeBinaryToWriter(message: Polygon, writer: jspb.BinaryWriter): void;
  static deserializeBinary(bytes: Uint8Array): Polygon;
  static deserializeBinaryFromReader(message: Polygon, reader: jspb.BinaryReader): Polygon;
}

Describe the solution you'd like

  static fromObject(from: Polygon.AsObject): Polygon;

Describe alternatives you've considered Writing a generic function to parse the field descriptors, but I don't know enough to make it work correctly, PLUS, it seems like a much better thing to be provided out of the box.

Additional context

alexandros-megas avatar Mar 08 '22 14:03 alexandros-megas

Maybe the proposed solution would be something like

  static fromObject(from: Partial<Polygon.AsObject>): Polygon;

This way, you can construct a partial message.

alexandros-megas avatar Mar 10 '22 20:03 alexandros-megas

We should fix this. #6 should help with this.

dibenede avatar Aug 12 '22 23:08 dibenede

For now I have built https://github.com/infodusha/from-protobuf-object Just in case you may want this in runtime

infodusha avatar Jan 23 '23 20:01 infodusha

how is it going on? i have same problem

bomsbro avatar Apr 27 '23 11:04 bomsbro

is there an update on this as I am facing the same problem

George-Madeley avatar Sep 23 '24 17:09 George-Madeley