Contentop
Contentop

Reputation: 1241

Decoding a google protobuff message after receiving it from a Web Socket in Node.JS

I am listening to a WebSocket and this WebSocket returns the data encoded in a Base64 binary bytes which is encoded by Google protobuff. I can't seem to find a way to decode it using Node.JS. Example of a data that was received:

CLP5gBASK3RibmIxbnVwZXB2dHloMGo3eHQ1czVsOTcwYTZ4YXJzcTZtNnB3bGE5eGgaFAoHQUxULTNCNhD58I/HAiCA35glGhAKA0JOQhCKsa2iASDQwPot

Edit 1:

This is the schema I am looking for:

message Account{
    int64 Height = 1;
    string owner = 2;
    repeated AssetBalance Balances = 3;
}

message AssetBalance{
    string Asset = 1;
    int64 Free = 2;
    int64 Frozen = 3;
    int64 Locked = 4;
}

I need to use the Account message I assume as the AssetBalance is here as it is a type inside Account.

Edit 2:

Fixed. the below solution works well. No need to use .result though. The eventual JSON Descriptor I used eventually was:

{
"nested": {
    "Account": {
        "fields": {
            "Height": {
                "type": "int64",
                "id": 1
            },
            "owner": {
                "type": "string",
                "id": 2
            },
            "Balances": {
                "repeated": true,
                "type": "AssetBalance",
                "id": 3
            }
        }
    },
    "AssetBalance": {
        "fields": {
            "Asset": {
                "type": "string",
                "id": 1
            },
            "Free": {
                "type": "int64",
                "id": 2
            },
            "Frozen": {
                "type": "int64",
                "id": 3
            },
            "Locked": {
                "type": "int64",
                "id": 4
            }
        }
    }
}

}

Upvotes: 1

Views: 3073

Answers (1)

Maicon Santana
Maicon Santana

Reputation: 350

try this approach:

var protobuf = require("protobufjs");
protobuf.parse.defaults.keepCase = true;
let root = protobuf.Root.fromJSON(JSON.parse("your json")
var message = root.lookupType("your type");
var buf = Buffer.from("CLP5gBASK3RibmIxbnVwZXB2dHloMGo3eHQ1czVsOTcwYTZ4YXJzcTZtNnB3bGE5eGgaFAoHQUxULTNCNhD58I/HAiCA35glGhAKA0JOQhCKsa2iASDQwPot","hex");
message.decode(buf).result;

more details: https://www.npmjs.com/package/protobufjs

Sample: https://github.com/maiconpintoabreu/Proto-Sample

Upvotes: 3

Related Questions