Skip to content

Commit 2a8dd74

Browse files
committed
Basic support for URL prefixes in google.protobuf.Any types.
Not all languages accept just the fully qualified name as type_url. In the official C++/C# protobuf library the type_url must at least start with a '/', otherwise the name is not resolved. Additionally we should be able to unpack types even if they have an URL prefix like type.googleapis.com/full.type.name. This commit just removes the URL prefix (similar as in other implementations I saw, e.g. python).
1 parent c43243b commit 2a8dd74

File tree

2 files changed

+15
-3
lines changed

2 files changed

+15
-3
lines changed

src/wrappers.js

+5-2
Original file line numberDiff line numberDiff line change
@@ -48,8 +48,9 @@ wrappers[".google.protobuf.Any"] = {
4848
// type_url does not accept leading "."
4949
var type_url = object["@type"].charAt(0) === "." ?
5050
object["@type"].substr(1) : object["@type"];
51+
// type_url prefix is optional, but path seperator is required
5152
return this.create({
52-
type_url: type_url,
53+
type_url: "/" + type_url,
5354
value: type.encode(type.fromObject(object)).finish()
5455
});
5556
}
@@ -62,7 +63,9 @@ wrappers[".google.protobuf.Any"] = {
6263

6364
// decode value if requested and unmapped
6465
if (options && options.json && message.type_url && message.value) {
65-
var type = this.lookup(message.type_url);
66+
// Only use fully qualified type name after the last '/'
67+
var name = message.type_url.substring(message.type_url.lastIndexOf("/") + 1);
68+
var type = this.lookup(name);
6669
/* istanbul ignore else */
6770
if (type)
6871
message = type.decode(message.value);

tests/comp_google_protobuf_any.js

+10-1
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,16 @@ tape.test("google.protobuf.Any", function(test) {
5151
}
5252
});
5353
test.ok(foo.foo instanceof Any.ctor, "should convert to Any in fromObject");
54-
test.same(foo.foo, { type_url: "Bar", value: protobuf.util.newBuffer([10, 1, 97]) }, "should have correct Any object when converted with fromObject");
54+
test.same(foo.foo, { type_url: "/Bar", value: protobuf.util.newBuffer([10, 1, 97]) }, "should have correct Any object when converted with fromObject");
55+
56+
var baz = Foo.fromObject({
57+
foo: {
58+
type_url: "type.someurl.com/Bar",
59+
value: [1 << 3 | 2, 1, 97] // value = "a"
60+
}
61+
});
62+
obj = Foo.toObject(baz, { json: true });
63+
test.same(obj.foo, { "@type": ".Bar", bar: "a" }, "should not care about prefix in type url");
5564

5665
test.end();
5766
});

0 commit comments

Comments
 (0)