Last active
November 7, 2024 10:02
-
-
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]
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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