Last active
June 30, 2016 14:51
-
-
Save tvdstaaij/044b3f4fdbe6ffcf6bec to your computer and use it in GitHub Desktop.
Convert ProtoBuf.js enum values to strings using reflection
This file contains 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
var _ = require('lodash'); | |
function stringifyEnums(message) { | |
_.forEach(message.$type.children, function(child) { | |
var type = _.get(child, 'element.resolvedType', null); | |
if (type && type.className === 'Enum' && type.children) { | |
var metaValue = _.find(type.children, { | |
id: message[child.name] | |
}); | |
if (metaValue && metaValue.name) | |
// Alternatively you can do something like: | |
// message[child.name + '_string'] = metaValue.name; | |
// To get access to both the raw value and the string. | |
message[child.name] = metaValue.name; | |
} | |
}); | |
return message; | |
} | |
// stringifyEnums only works for direct children of one message. | |
// This function handles enums in submessages as well. | |
function stringifyEnumsRecursive(message) { | |
message = stringifyEnums(message); | |
_.forEach(message, function(subMessage, key) { | |
if (_.isObject(subMessage) && subMessage.$type) | |
message[key] = stringifyEnumsRecursive(message[key]); | |
}); | |
return message; | |
} | |
module.exports = { | |
stringifyEnums: stringifyEnums, | |
stringifyEnumsRecursive: stringifyEnumsRecursive | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
or better go this way without lodash
utils.coffee