From 2a8dd74fca70d4e6fb41328a7cee81d1d50ad7ad Mon Sep 17 00:00:00 2001 From: Manfred Rudigier Date: Thu, 29 Jun 2017 10:30:10 +0200 Subject: [PATCH] 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). --- src/wrappers.js | 7 +++++-- tests/comp_google_protobuf_any.js | 11 ++++++++++- 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/src/wrappers.js b/src/wrappers.js index 3c905e3e6..710aab0d2 100644 --- a/src/wrappers.js +++ b/src/wrappers.js @@ -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() }); } @@ -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); diff --git a/tests/comp_google_protobuf_any.js b/tests/comp_google_protobuf_any.js index ee870980d..9027754af 100644 --- a/tests/comp_google_protobuf_any.js +++ b/tests/comp_google_protobuf_any.js @@ -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(); });