Skip to content

Instantly share code, notes, and snippets.

@sskanishk
Last active November 7, 2024 10:02
Show Gist options
  • Save sskanishk/391c69669dffa9ed0a9ddbf9836ebd40 to your computer and use it in GitHub Desktop.
Save sskanishk/391c69669dffa9ed0a9ddbf9836ebd40 to your computer and use it in GitHub Desktop.
The code effectively serializes and deserializes data using Protobuf, ensuring data integrity and efficiency. It loads the Protobuf definition, verifies the payload, and converts it into a Protobuf message before encoding and decoding it. [protobuf sample code]
const protobuf = require('protobufjs');
// Load the generated Person class
const root = protobuf.loadSync('person.proto');
root.resolveAll();
// console.log("root ", root)
if (!root) {
console.error('Failed to load person.proto');
process.exit(1);
}
const Person = root.lookupType('Person');
// Payload
const payload = {
name: 'Alice',
id: 123,
email: '[email protected]',
cool: '123'
}
// Verify Payload
const err = Person.verify(payload);
if(err) {
console.error('Invalid payload (not an object)');
process.exit(1);
}
// conversion / filter - remove unwanted fileds from payload by comparing proto file
const fromObj = Person.fromObject(payload);
console.log("fromObj ", fromObj);
// Serialization
const person = Person.create(payload);
const buffer = Person.encode(person).finish();
// Deserialization
const decodedPerson = Person.decode(buffer);
console.log(decodedPerson.name);
// Simply do npm init and npm install protobufjs
// node index.js
syntax = "proto3";
message Person {
string name = 1;
int32 id = 2;
string email = 3;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment