首页 > 解决方案 > 在 protobuf.js 中自动包装和解包 wrappers.proto 类型

问题描述

我一直在使用 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 来实现这一点?

标签: javascripttypescriptprotobuf.js

解决方案


我不认为你可以。包装器是消息,我认为 protobuf.js 没有选项可以为您取消包装这些值。

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

但看起来 proto3 的“可选”标签又回来了。这意味着您可以编写:

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

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

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

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

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


推荐阅读