提问者:小点点

如何使用节点grpc将枚举解析为字符串值?


将grpc与Node一起使用,对我的查询的响应中的枚举将解析为整数值。但是,当我使用BloomRPC进行相同的查询时,枚举将解析为整数值。

是否有参数或选项可以强制使用Node grpc将这些枚举解析为字符串?


共2个答案

匿名用户

在我们的项目中,我们使用枚举通过消除人为错误来帮助我们确保有限可能性集的完整性。当我们有协议缓冲区枚举如此方便时,为什么我们需要记住字符串值是什么?因此,我们使用. proto作为真理的来源;这是我们的规则。

要做到这一点,请遵循以下步骤,这些步骤是为ES6代码编写的。

  1. 中定义gRPC/Protobuf枚举。proto文件
// life.proto
syntax = 'proto3';
package life;

enum Choices
{
  EAT = 0;
  DRINK = 1;
  SLEEP = 2;
  CODE = 3;
  SKI = 4;
}
$ npm i -s @grpc/proto-loader @grpc/grpc-js
// myNodeApp.js
import * as grpc from '@grpc/grpc-js'
import * as protoLoader from '@grpc/proto-loader'
import path from 'path'

// these options help make definitions usable in our code
const protoOptions = {
  keepCase: true,
  longs: String,
  enums: String,
  defaults: true,
  oneofs: true
}

// this allows us to prepare the path to the current dir
const dir = path.dirname(new URL(import.meta.url).pathname)
// this loads the .proto file
const lifeDef = protoLoader.loadSync(path.join(dir, 'life.proto'), protoOptions)
// this loads the package 'life' from the .proto file
const life = grpc.loadPackageDefinition(lifeDef).life
// myNodeApp.js (cont'd)
console.log(life.Choices)

/* stdout */
{
  format: 'Protocol Buffer 3 EnumDescriptorProto',
  type: {
    value: [ [Object], [Object], [Object], [Object], [Object] ],
    name: 'Choices',
    options: null
  },
  fileDescriptorProtos: [
    <Buffer 0a ... 328 more bytes>
  ]
}

...更深入地看。。。

console.log(life.Choices.value)

/* stdout */
{
  value: [
    { name: 'EAT', number: 0, options: null },
    { name: 'DRINK', number: 1, options: null },
    { name: 'SLEEP', number: 2, options: null },
    { name: 'CODE', number: 3, options: null },
    { name: 'SKI', number: 4, options: null }
  ],
  name: 'Choices',
  options: null
}

// myNodeApp.js
const myDay = { // plain JSON (or define a gRPC message, same same)
  dawn: life.Choices.type.value[1].name,
  morning: life.Choices.type.value[0].name,
  afternoon: life.Choices.type.value[4].name,
  evening: life.Choices.type.value[3].name,
  night: life.Choices.type.value[2].name
}

您可以编写访问器或实用程序函数来管理密钥查找(通过传递导入的grpc枚举和索引),如下所示:

export const getEnumByName = function (protoEnum, needle) {
  return protoEnum.type.value.find(p => {
    return p.name === needle
  })
}

export const getEnumByNum = function (protoEnum, needle) {
  return protoEnum.type.value.filter(p => {
    return p.number = needle
  })
}

export const getEnumKeys = function (protoEnum, key = 'name') {
  return protoEnum.type.value.map(p => {
    return p[key]
  })
}

其他答案中已经介绍了反转消息并为其赋值,只需使用表示枚举名称的字符串将枚举字段设置为字符串值,您可以猜到,该字符串表示使用上述代码访问的枚举名称。

这就是我们的做法。干净简单,只是有一点模糊,直到有一天你看到“引擎盖下”。

了解有关@grpc/proto loader和@grpc/grpc js的更多信息。希望这对野外的人有所帮助。:)

匿名用户

如果您使用的是@grpc/proto-loader库,您可以将选项enum设置为值String(不是字符串“String”,构造函数String)。然后所有枚举值都将由它们的名称字符串表示。