Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

"Google Protobuf Any" javscript example #1082

Open
psaelango opened this issue Jul 10, 2018 · 4 comments
Open

"Google Protobuf Any" javscript example #1082

psaelango opened this issue Jul 10, 2018 · 4 comments

Comments

@psaelango
Copy link

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 #435

@Bizarrus
Copy link

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
Copy link

stivenson commented Jul 25, 2019

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

@Bizarrus
Copy link

Bizarrus commented Jul 26, 2019

<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
Copy link

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?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants