Javascript protobuf example

http://stackoverflow.com/q/21802866/1928023

by Daedalus

HTML

<script src="https://unpkg.com/[email protected]/dist/protobuf.min.js"></script>
<script src="https://unpkg.com/[email protected]/dist/bytebuffer.js"></script>
<script src="https://unpkg.com/[email protected]/dist/long.js"></script>
<h1>Javascript protobuf example</h1>
Demo for <a href="http://stackoverflow.com/q/21802866/1928023">this SO question</a>.

<h2>Initial Object</h2>
<pre id="obj"></pre>
<h2>Encoded buffer</h2>
<pre id="buff"></pre>
<h2>Decoded Object</h2>
<pre id="result"></pre>

JavaScript

let message = function () {
    var proto = {
        package : 'message',
        messages : [
            {
                name : 'arguments',
                fields : [
                    {
                        rule : 'repeated',
                        type : 'string',
                        name : 'repos',
                        id : 1
                    },
                    {
                        rule : 'repeated',
                        type : 'string',
                        name : 'labels',
                        id : 2
                    },
                    {
                        rule : 'repeated',
                        type : 'string',
                        name : 'milestones',
                        id : 3
                    },
                    {
                        rule : 'required',
                        type : 'string',
                        name : 'username',
                        id : 4
                    },
                    {
                        rule : 'optional',
                        type : 'bool',
                        name : 'with_comments',
                        id : 5
                    },
                    {
                        rule : 'optional',
                        type : 'bool',
                        name : 'without_comments',
                        id : 6
                    }
                ],
            }
        ]
    };
    
    return protobuf.Root.fromJSON(proto)
};

(function(message) {
    
    var data = {
        repos : ['a', 'b', 'c'],
        labels: ['d', 'e', 'f'],
        milestones : ['g', 'h', 'i'],
        username : 'jgb'
    }
    document.getElementById('obj').innerHTML = JSON.stringify(data, null, 2);
    
    var request = new message.arguments(data);
    
    // Convert request data to base64
    var base64String = request.toBase64();
    console.log(base64String);
    document.getElementById('buff').innerHTML = base64String;
    
    //...