@bufbuilding/protoc-gen-grpc-es (英语)
protoc-gen-grpc-es 生成 型态好,平庸 (原始内容存档于2018-10-21) (英语). gRPC 根节 页:1 Protobuf-ES (英语) (单位:千美元)@bufbuild/protobuf),用于JavaScript和TypeScript的ergoomic和现代Protobuf库.
插入到您已有的 @grpc/grpc-js 频道和服务器.
这是已建工程的兼容层 @grpc/grpc-js。生成的客户端和服务器插入您现有的 gRPC 频道和服务器,但直接序列化 Protobuf-ES 消息。 这使得您可以升级到更好的Protobuf软件包,而不触及您的RPC堆栈.
[TIP] 用于新项目 连接-ES 换句话说 Connect除了自身之外还会说出gRPC和gRPC-Web协议,因此现有的gRPC客户端可以称一个Connect服务器不变. 但您也可以获得普通的 HTTP API
curl,并生成客户端 每种主要语言包括你的前端.protoc-gen-grpc-es只存在如此已建基于当前 gRPC 代码库@grpc/grpc-js可以在今天获得Protobuf-ES的改进而无需完全重写.
开始
安装
安装运行时库和 protoc 插件, 运行 :
npm install @bufbuild/protobuf @grpc/grpc-js
npm install --save-dev @bufbuild/protoc-gen-es @bufbuild/protoc-gen-grpc-es @types/node
生成代码
我们建议使用 buf 生成代码。 添加新内容 buf.gen.yaml 配置文件 :
# Learn more: https://buf.build/docs/configuration/v2/buf-gen-yaml
version: v2
inputs:
- directory: proto
plugins:
- local: protoc-gen-es
out: src/gen
opt: target=ts
- local: protoc-gen-grpc-es
out: src/gen
opt: target=ts
将您的 .proto 文档中 ./proto 目录,然后运行:
npx buf generate
使用量
对于每个包含服务的Protobuf文件,插件生成一个 _grpc.ts 文件旁边 _pb.ts 文件来自 protoc-gen-es. 例如,以下服务:
syntax = "proto3";
package example;
service ElizaService {
rpc Say(SayRequest) returns (SayResponse);
}
message SayRequest {
string sentence = 1;
}
message SayResponse {
string sentence = 1;
}
生成下列导出 eliza_grpc.ts数字 :
ElizaServiceDefinition编号:@grpc/grpc-js服务定义.ElizaServiceServer: 服务器执行的接口.ElizaServiceClient:每个RPC都有打入方法的客户端.
要执行服务器 :
import * as grpc from "@grpc/grpc-js";
import { ElizaServiceDefinition, type ElizaServiceServer } from "./gen/eliza_grpc.js";
const implementation: ElizaServiceServer = {
say(call, callback) {
callback(null, { sentence: `You said: ${call.request.sentence}` });
},
};
const server = new grpc.Server();
server.addService(ElizaServiceDefinition, implementation);
server.bindAsync("localhost:50051", grpc.ServerCredentials.createInsecure(), () => {});
和客户打电话:
import * as grpc from "@grpc/grpc-js";
import { ElizaServiceClient } from "./gen/eliza_grpc.js";
const client = new ElizaServiceClient("localhost:50051", grpc.credentials.createInsecure());
client.say({ sentence: "Hi" }, (error, response) => {
if (error) {
throw error;
}
console.log(response?.sentence);
});
插件选项
protoc-gen-grpc-es 支持与 protoc-gen-es数字 :
| 选项 | 数值 | 默认 | 说明 |
|---|---|---|---|
target | js, (中文(简体) ), ts, (中文(简体) ), dts (与 +(中文(简体) ) | js+dts | 要生成的文件 . |
import_extension | none, (中文(简体) ), js, (中文(简体) ), ts | none | 在导入路径中使用的文件扩展名 . |
js_import_style | module, (中文(简体) ), legacy_commonjs | module | 使用ECMAS脚本 import编号 :export 或 常见JS require。 。 。 . |
keep_empty_files | true, (中文(简体) ), false | false | 保留生成的文件, 即使它们没有包含服务 . |
ts_nocheck | true, (中文(简体) ), false | false | 生成 a // @ts-nocheck 在每个文件的顶部注释. |
elide_plugin_version | true, (中文(简体) ), false | false | 从生成的文件头关闭插件版本 . |
确保使用相同的 target 财务报告和审定财务报表 import_extension 用于两个插件的值,以便生成 _grpc 文件可以从生成的文件导入 _pb 文档.