javascript - 在 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 来实现这一点?
解决方案
我不认为你可以。包装器是消息,我认为 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 的作者。
推荐阅读
- python - Pandas - 需要对文件名进行多次拆分操作以使用 Ticker 和 Exchange 创建 df 以导入 SQL
- linux - 为什么Linux上的ECDSA签名不能在Windows上验证成功?
- python - 如何在远程 SSH 客户端的 VS 代码中使用 Python 调试器
- php - 如何过滤while循环中的项目?
- automation - PyDirectInput 鼠标移动非常敏感
- mysql - 如何使用 mysqldump 在 mysql 工作台中创建关系表的逻辑备份?
- python - 在 Docker 容器中使用 Python 编写输出
- sql-server - 使用游标将数据库声明为变量?SQL 服务器/T-SQL
- r - How to calculate all pairwise abs differences among many variables in R
- javascript - CSS Global margin not working inside @media