Skip to content

Instantly share code, notes, and snippets.

@lautarodragan
Last active January 30, 2023 15:41
Show Gist options
  • Save lautarodragan/52fd05a9e261b7e22c27f4eae41baf1a to your computer and use it in GitHub Desktop.
Save lautarodragan/52fd05a9e261b7e22c27f4eae41baf1a to your computer and use it in GitHub Desktop.
protobuf.js wrapper types + null
syntax = "proto3";
import "google/protobuf/wrappers.proto";
message MyHappyProto {
string id = 1;
google.protobuf.StringValue name = 2;
google.protobuf.StringValue address = 3;
google.protobuf.StringValue something = 4;
google.protobuf.StringValue nullable = 5;
}
$ npm start
> proto@1.0.0 start
> node index.js
jsonInput {
id: '1',
name: { value: 'name' },
address: {},
something: undefined,
nullable: null
}
Calling fromObject...
StringValue.fromObject { value: 'name' }
StringValue.fromObject {}
Calling toObject...
StringValue.toObject StringValue { value: 'name' } object
StringValue.toObject StringValue {} object
decodedHappyProto { id: '1', name: 'name', address: null }
import protobuf from "protobufjs";
protobuf.wrappers['.google.protobuf.StringValue'] = {
fromObject(value) {
console.log(' StringValue.fromObject', value)
return this.fromObject(value)
},
toObject(message, options) {
console.log(' StringValue.toObject', message, typeof message)
if (Object.keys(message).length === 0)
return null;
else if (message.value)
return message.value
},
}
// Load MyHappyProto
const proto = await protobuf.load("MyHappyProto.proto")
const MyHappyProto = proto.lookupType('MyHappyProto')
const jsonInput = {
id: '1',
name: { value: 'name' },
address: { },
something: undefined,
nullable: null,
}
console.log('jsonInput', jsonInput)
// Validate Input
const error = MyHappyProto.verify(jsonInput)
if (error) throw error
// JSON -> Message
console.log('Calling fromObject...')
const myHappyProtoMessage = MyHappyProto.fromObject(jsonInput)
// Message -> Bytes
const encodedMessageBuffer = MyHappyProto.encode(myHappyProtoMessage).finish();
// Bytes -> Message
const decodedHappyProtoMessage = MyHappyProto.decode(encodedMessageBuffer);
// Message -> JSON
console.log('Calling toObject...')
const decodedHappyProto = MyHappyProto.toObject(decodedHappyProtoMessage);
console.log('decodedHappyProto', decodedHappyProto)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment