Can anyone please provide an example for https://developers.google.com/protocol-buffers/docs/proto3#any
I couldn't able to use the example provided in https://github.com/google/protobuf/issues/2612
Bo, we need to add documentation for Any API in javascript.
Any documentation or guide for Any?
var any = new proto.google.protobuf.Any();
var msg = new proto.jspb.test.TestAllTypes();
fillAllFields(msg);
any.pack(msg.serializeBinary(), 'jspb.test.TestAllTypes');
assertEquals('type.googleapis.com/jspb.test.TestAllTypes',
any.getTypeUrl());
var msg2 = any.unpack(
proto.jspb.test.TestAllTypes.deserializeBinary,
'jspb.test.TestAllTypes');
checkAllFields(msg, msg2);
Man the documentation for javascript is scarce. But for any one using the google-protobuf node module in angular, you can include the use of Any type in the below fashion. I recommend anyone using the javascript API to look through the tests because you won't find documentation as of yet.
var google_protobuf_any_pb = require('google-protobuf/google/protobuf/any_pb.js');
let any_pb = new google_protobuf_any_pb.Any;
@TeBoring I found the unit test, however I can't understand how that can be useful as documentation for how to actually use the code. Obviously if you have the actual message type of a byte string, you can deserialize it. You don't even need the type url string.
When consuming an Any field you only have access to the serialized byte string and the type URL.
Hence you need to somehow get the actual type from the URL, which doesn't seem to be documented anywhere, unless I'm missing something.
Concretely, here's how the Java implementation looks like
java.lang.Class<T> clazz)
throws com.google.protobuf.InvalidProtocolBufferException {
if (!is(clazz)) {
throw new com.google.protobuf.InvalidProtocolBufferException(
"Type of the Any message does not match the given class.");
}
if (cachedUnpackValue != null) {
return (T) cachedUnpackValue;
}
T defaultInstance =
com.google.protobuf.Internal.getDefaultInstance(clazz);
T result = (T) defaultInstance.getParserForType()
.parseFrom(getValue());
cachedUnpackValue = result;
return result;
}
public static final int TYPE_URL_FIELD_NUMBER = 1;
private volatile java.lang.Object typeUrl_;
Is there an equivalent of com.google.protobuf.Internal.getDefaultInstance(clazz) for javascript?
I don't see any way in Javascript to do that. I work around this by including the type, as an enum, as part of my message struct and then using a switch case to properly unpack the any. Not dynamic I know, but it's the only way I know to do it.
@chrisplusplus that's what I ended up doing too
Most helpful comment
Man the documentation for javascript is scarce. But for any one using the google-protobuf node module in angular, you can include the use of Any type in the below fashion. I recommend anyone using the javascript API to look through the tests because you won't find documentation as of yet.