Skip to content

Instantly share code, notes, and snippets.

@tvdstaaij
Last active June 30, 2016 14:51
Show Gist options
  • Save tvdstaaij/044b3f4fdbe6ffcf6bec to your computer and use it in GitHub Desktop.
Save tvdstaaij/044b3f4fdbe6ffcf6bec to your computer and use it in GitHub Desktop.
Convert ProtoBuf.js enum values to strings using reflection
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
};
@timCF
Copy link

timCF commented Jun 30, 2016

or better go this way without lodash

utils.coffee

module.exports =
    stringifyEnums: (message) ->
        utils = @
        if (message and message.$type and message.$type.children)
            message.$type.children.forEach((child) ->
                if (message[child.name] and child.element.resolvedType)
                    switch child.element.resolvedType.className
                        when 'Enum'
                            dict = child.element.resolvedType.children.reduce(((acc, {id: id, name: name}) -> acc[id] = name ; acc), {})
                            if child.repeated
                                message[child.name] = message[child.name].map((el) -> dict[el])
                            else
                                message[child.name] = dict[message[child.name]]
                        when 'Message'
                            if child.repeated
                                message[child.name] = message[child.name].map((el) -> utils.stringifyEnums(el))
                            else
                                message[child.name] = utils.stringifyEnums(message[child.name]))
        message

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment