Skip to content

Commit

Permalink
Basic support for URL prefixes in google.protobuf.Any types.
Browse files Browse the repository at this point in the history
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).
  • Loading branch information
manni83 committed Jun 29, 2017
1 parent c43243b commit 2a8dd74
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 3 deletions.
7 changes: 5 additions & 2 deletions src/wrappers.js
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,9 @@ wrappers[".google.protobuf.Any"] = {
// type_url does not accept leading "."
var type_url = object["@type"].charAt(0) === "." ?
object["@type"].substr(1) : object["@type"];
// type_url prefix is optional, but path seperator is required
return this.create({
type_url: type_url,
type_url: "/" + type_url,
value: type.encode(type.fromObject(object)).finish()
});
}
Expand All @@ -62,7 +63,9 @@ wrappers[".google.protobuf.Any"] = {

// decode value if requested and unmapped
if (options && options.json && message.type_url && message.value) {
var type = this.lookup(message.type_url);
// Only use fully qualified type name after the last '/'
var name = message.type_url.substring(message.type_url.lastIndexOf("/") + 1);
var type = this.lookup(name);
/* istanbul ignore else */
if (type)
message = type.decode(message.value);
Expand Down
11 changes: 10 additions & 1 deletion tests/comp_google_protobuf_any.js
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,16 @@ tape.test("google.protobuf.Any", function(test) {
}
});
test.ok(foo.foo instanceof Any.ctor, "should convert to Any in fromObject");
test.same(foo.foo, { type_url: "Bar", value: protobuf.util.newBuffer([10, 1, 97]) }, "should have correct Any object when converted with fromObject");
test.same(foo.foo, { type_url: "/Bar", value: protobuf.util.newBuffer([10, 1, 97]) }, "should have correct Any object when converted with fromObject");

var baz = Foo.fromObject({
foo: {
type_url: "type.someurl.com/Bar",
value: [1 << 3 | 2, 1, 97] // value = "a"
}
});
obj = Foo.toObject(baz, { json: true });
test.same(obj.foo, { "@type": ".Bar", bar: "a" }, "should not care about prefix in type url");

test.end();
});

0 comments on commit 2a8dd74

Please sign in to comment.