protobufjs / protobuf.js

Protocol Buffers for JavaScript & TypeScript.
Other
9.87k stars 1.41k forks source link

"Google Protobuf Any" javscript example #1082

Open psaelango opened 6 years ago

psaelango commented 6 years ago

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/dcodeIO/protobuf.js/issues/435

Bizarrus commented 5 years ago

I've found the solution by inspect an packed Message!

For an easy usage, you can run these on first initialization and store the Any to the globals from Node.js. Then, you can access these all the time on each side:

protobuf.load('google/protobuf/any.proto', function(err, root) {
    if(err) {
        throw err;
    }

    global.Any = root.lookup('Any');
});

And here is an Example:

var test = Any.create({
    type_url:    'whatever',
    value:        <Buffer>
});

console.log('Instance', test);
console.log('Packed', Any.encode(test).finish());
stivenson commented 5 years ago

hi @Bizarrus , a cordial greeting. a favor, what would be an example of the value in "< Buffer >"? thanks bro..

Bizarrus commented 5 years ago

<Buffer> is an value of ArrayBuffer, Uint8Array or an another ProtoInstance (which was created before) for a sample.

If you wan't an real example, here is it:

Demo.proto

syntax = "proto3";

message Demo {
    string demo = 1;
}

Script

const protobuf = require('protobufjs');

protobuf.load('google/protobuf/any.proto', function(error, root) {
    if(error) {
        throw error;
    }

    global.Any = root.lookup('Any');

    protobuf.load('Demo.proto', function(error, root) {
        if(error) {
            throw error;
        }

        let Demo = root.lookup('Demo');
        let test = Demo.create({
            demo: 'Hello World'
        });

        console.log(test);

        var any = Any.create({
            type_url:    'whatever',
            value:       test,
            // value:       Demo.encode(test).finish() // Or as packed buffer
        });

        console.log('Instance', any);
        console.log('Packed', Any.encode(any).finish());
    });
});

Result image

stivenson commented 5 years ago

hi all, a cordial greeting, please @Bizarrus , a question, in that example i always get:

Packed <Buffer 0a 08 77 68 61 74 65 76 65 72 12 00> a buffer instead of json data.

Why can it be?