protocolbuffers / protobuf-javascript

BSD 3-Clause "New" or "Revised" License
345 stars 66 forks source link

JS generator missing jspb.generate_from_object option #96

Open hochhaus opened 8 years ago

hochhaus commented 8 years ago

The comment for jspb.Message.GENERATE_FROM_OBJECT states:

 *     NOTE: By default no protos actually have a fromObject method. You need to
 *     add the jspb.generate_from_object options to the proto definition to
 *     activate the feature.

However, no such option is currently implemented in the open sourced version. I see the code which generates output for this option (GenerateClassFromObject) but it is invoked 0 times.

~/protobuf$ grep -r GenerateClassFromObject .
./src/google/protobuf/compiler/js/js_generator.cc:void Generator::GenerateClassFromObject(const GeneratorOptions& options,
./src/google/protobuf/compiler/js/js_generator.h:  void GenerateClassFromObject(const GeneratorOptions& options,

Can the jspb.generate_from_object option be open sourced?

ykensuke commented 3 years ago

+1

kamok commented 3 years ago

Can someone explain how we would use the new fromObject method? I currently use https://github.com/agreatfool/grpc_tools_node_protoc_ts to generate TypeScript types from proto files. Does the PR from protocolbuffers/protobuf#8488 mean that the typescript generation lib need to be updated as well (simple typing change?).

wapa5pow commented 2 years ago

I created example repository to generate fromObject method https://github.com/wapa5pow/protoc-node . It compiles protoc with fromObject.

sglim commented 2 years ago

I created an npm library to serialize pure javascript objects compatible with the protobuf class. https://www.npmjs.com/package/protobuf-js-from-object

Modifying protoc is too heavy and sometimes hard to apply due to your dependency system. So I add a simple solution to serialize a pure object to protobuf binary.

The serialized binary can be deserialized, and you can also send it via networks. The solution is a bit hacky, but it doesn't take many resources like memory or CPU.

For example:

// Serialize
const buffer = serializeFromObject(pureObj, pb.Burger);
// Deserialize
const burger = pb.Burger.deserializeBinary(buffer);

Make sure that the pure object should have all properties as a key even if the property's value is undefined.

kcarlson commented 1 year ago

this worked for me: https://gist.github.com/kcarlson/0e69fbce5bff8ca2670af83db346df19

leafstark commented 1 month ago

https://www.npmjs.com/package/proto-msg-converter This can be helpful