【问题标题】:Automatically wrapping & unwrapping wrappers.proto types in protobuf.js在 protobuf.js 中自动包装和解包 wrappers.proto 类型
【发布时间】:2020-09-09 09:07:34
【问题描述】:

我一直在使用 protobuf.js(命令行工具)pbjs 和 pbts 为我定义的 .proto 文件生成我的 js 和 typescript 类。我从我的后端 API 收到一个 json 响应,我希望将其反序列化为 protobuf 生成的类。推荐的方法是使用接受 json 对象的 fromObject 方法。 假设我有

message ChangeEvent {
  string source = 1;
  google.protobuf.StringValue code = 2;
}

我希望能够通过:

const changeEventWithCode = {
  source = 'test',
  code = 'code',
}

const changeEventWithoutCode = {
  source = 'test',
  code = null,
}

并让它们都编码和解码为相同的东西。但是,如果我想设置代码字符串,我必须这样做:

const changeEventWithCode = {
  source = 'test',
  code = {
    value: 'code',
  },
}

我希望 fromObject 可以处理这个问题,但它没有 - 有什么方法可以挂钩一些自定义来做到这一点。或者,如何使用 typescript 使用 protobufjs 来实现这一点?

【问题讨论】:

    标签: javascript typescript protobuf.js


    【解决方案1】:

    我不认为你可以。包装器是消息,我认为 protobuf.js 没有选项可以为您解箱。

    但是ts-proto 可以!对于google.protobuf.StringValue code,它将创建一个属性签名code: string | undefined。听起来这就是你想要的。

    但 proto3 的“可选”标签似乎又回来了。这意味着你可以写:

    message ChangeEvent {
      string source = 1;
      optional string code = 2;
    }
    

    这仍然是一个实验性功能,在 protoc v3.12.0 中添加。而且你需要一个支持它的 typescript 插件。

    还有一个:protobuf-ts。它将生成以下打字稿:

    interface ChangeEvent {
      source: string;
      code?: string
    }
    

    免责声明:我是protobuf-ts的作者。

    【讨论】:

      猜你喜欢
      • 2018-07-29
      • 2016-11-19
      • 2015-09-24
      • 1970-01-01
      • 1970-01-01
      • 2016-12-29
      • 1970-01-01
      • 2019-05-10
      • 1970-01-01
      相关资源
      最近更新 更多