Skip to main content

protobuf-web

ts-proto

  • nice-grpc 使用
  • 生成单独文件
optdefaultnotes
contextfalse
forceLongnumberlong,string
esModuleInteropfalse
envbothnode,browser
useOptionalsnonemessage,all
exportCommonSymbolstrue
oneofunions
unrecognizedEnumfalse是否包含 UNRECOGNIZED=-1
lowerCaseServiceMethodstrue
snakeToCameltrue
outputEncodeMethodstrueencode,decode
outputJsonMethodstruefromJSON,toJSON
stringEnumsfalse要求 outputEncodeMethods=false
outputClientImplgrpc-web
returnObservablefalseObservable<T>
addGrpcMetadata要求 nestJs=true
addNestjsRestParameter要求 nestJs=true
nestJsfalse
useDatetruegoogle.protobuf.Timestamp
useObjectIdfalsemongodb.ObjectId
outputSchemafalse
outputTypeRegistryfalse$type
outputServicesgrpc-js,nice-grpc,generic-definitions,none,false
metadataTypeFoo@./some-file
useAsyncIterable
emitImportedFiles
fileSuffix
importSuffix
enumsAsLiteralsas const
useExactTypestruefromPartial
unknownFieldsfalse
onlyTypesfalse只生成类型
usePrototypeForDefaultsObject.create
useJsonWireFormatfalse
useNumericEnumForJsonfalse
  • useOptionals - field: Message | undefined, field?: Message
  • exportCommonSymbols - export DeepPartial
  • fromJSON - 会设置默认值
  • toJSON - 不会忽略默认值 - 未来可能会
  • outputClientImpl - grpc-web, twirp, grpc-js, nextjs
  • useContext - 添加一个额外的 context 参数
outputServices=nice-grpc,outputServices=generic-definitions,useExactTypes=false,esModuleInterop=true,forceLong=long,outputTypeRegistry=true
// Basic gRPC
interface Rpc {
request(service: string, method: string, data: Uint8Array): Promise<Uint8Array>;
}

protobufjs

  • 开发不活跃
caution
  • 不支持 ESM #1230
  • protobufjs 生成的 JSON 缺少信息
    • 无 comment
    • option 只能记录 1 个
      • 无法记录 repeated option
    • 无法记录嵌套 option
  • option 为对象会失败 #1788
npm add -D protobufjs-cli

# -t,--target - json, json-module, proto2, proto3, static, static-module
pbjs -t json file1.proto file2.proto > bundle.json
pbjs -t json-module -w commonjs -o bundle.js file1.proto file2.proto

pbjs -t static-module -w commonjs -o compiled.js file1.proto file2.proto

pbts -o compiled.d.ts compiled.js
pbjs -t static-module file1.proto file2.proto | pbts -o bundle.d.ts -

#
pbjs -t json -p ./protos/bundles/ ./protos/core/**/*.proto -o src/protos/pb.json
pbjs -t static-module -p ./protos/bundles/ ./protos/core/**/*.proto -w es6 -o src/protos/pb.js
pbts -o src/protos/pb.d.ts src/protos/pb.js
sourcelibproscons
.protofull简单,不需要编译
jsonlight单 bundle,不需要 parse
staticminimal不需要 eval, 有 comment代码非常长

| pbjs | | ------------- | ------------------ | | --alt-comment | 解析出更多 comment | | -w | es6 |

import * as $protobuf from 'protobufjs/light';

// 可以有多个 ROOT
$protobuf.roots['default'] = new $protobuf.Root();