Open yagop opened 7 years ago
:thinking:
You can overwrite function toObject
by using Protobuf.wrappers
const protobuf = require('protobufjs')
protobuf.wrappers['.main.Decimal'] = {
toObject(message, options) {
const originOutput = this.toObject(message, options)
if (message.type === 2) {
originOutput.content = UserProfile.toObject(UserProfile.decode(Buffer.from(message.content, 'base64')))
}
return originOutput
},
fromObject(object) {
console.log('user fromObject')
return this.toObject(object)
},
}
const proto = `
package main;
message Decimal {
required sint64 mantisa = 1;
required sint32 exponent = 2;
optional uint32 type = 3;
optional bytes content = 4;
}
message User {
required Decimal user = 1;
}
message UserProfile {
required string name = 1;
}
`
const root = protobuf.parse(proto).root
const UserProfile = root.lookupType('main.UserProfile')
const Decimal = root.lookupType('main.Decimal')
const User = root.lookupType('main.User')
const options = {
keepCase: true,
bytes: String, // bytes as base64 encoded strings
}
const user = User.create({
user: Decimal.create({
mantisa: 1,
exponent: 0,
type: 2,
content: UserProfile.encode({ name: 'Tom' }).finish(),
}),
})
const buffer2 = User.encode(user).finish()
const decoded2 = User.decode(buffer2)
console.log(User.toObject(decoded2, options))
protobuf.js version: 6.8.0
Hello, I'm trying to overwriting
toObject
in a custom class, but it seems is not being possible or I'm doing it wrong.Output: