Example of using protobuf in JavaScript

 avatar
unknown
javascript
2 years ago
1.9 kB
8
Indexable
const protobuf = require("protobufjs");

// Define the structure of your data using Protobuf's TypeScript-like syntax
const proto = `
  syntax = "proto3";
  
  message Game {
    string _id = 1;
    string state = 2;
    string creator = 3;
    string creatorUsername = 4;
    string creatorAvatar = 5;
    int32 amount = 6;
    string createdAt = 7;
    string player = 8;
    string playerAvatar = 9;
    string playerUsername = 10;
    string id = 11;
  }
  
  message GameList {
    repeated Game games = 1;
  }
`;

// Compile the proto definition to a type that can be used to encode data
const root = protobuf.Root.fromJSON(protobuf.parse(proto));
const Game = root.lookupType("Game");
const GameList = root.lookupType("GameList");

const data = [
  {
    "_id": "63a40f6e0db326412767d0fd",
    "state": "playing",
    "creator": "63a04b9de0de414e78325999",
    "creatorUsername": "yash_sharma520",
    "creatorAvatar": "avatar-m-3",
    "amount": 50,
    "createdAt": "2022-12-22T08:03:58.419Z",
    "player": "63a04ea7e0de414e78326b2b",
    "playerAvatar": "avatar-m-3",
    "playerUsername": "aamir101",
    "id": "63a40f6e0db326412767d0fd"
  },
  {
    "_id": "63ab9b8fae6172b35e56285c",
    "state": "playing",
    "creator": "63aad3fca6b70bd292c48f8e",
    "creatorUsername": "nurtaj_ansari931",
    "creatorAvatar": "avatar-m-2",
    "amount": 50,
    "createdAt": "2022-12-28T01:27:43.113Z",
    "player": "63a998bb6f2f23b4e005eb93",
    "playerAvatar": "avatar-m-4",
    "playerUsername": "9652480051139",
    "id": "63ab9b8fae6172b35e56285c"
  }
];

// Convert the JavaScript data to a Protobuf message
const games = data.map(game => Game.create(game));
const gameList = GameList.create({ games });

// Encode the Protobuf message to a binary array
const binaryData = GameList.encode(gameList).finish();

// The `binaryData` array can now be efficiently sent over the network
Editor is loading...