【问题标题】:Importing Proto File to another ProtoFile in NodeJS在 NodeJS 中将 Proto 文件导入另一个 ProtoFile
【发布时间】:2021-05-02 16:49:20
【问题描述】:

我对 Protocol Buffers 很陌生。

我注意到 grpc proto-loader 模块只需要加载一个 proto 定义文件,因此我将其加载到我的代码中,如下所示:

const PROTO_PATH = `${path.resolve(__dirname, '..')}${path.sep}protos${path.sep}index.proto`;
const packageDefinition = protoLoader.loadSync(PROTO_PATH, {
    keepCase: true,
    longs: String,
    enums: String,
    defaults: true,
    oneofs: true
});

let indexProto = grpc.loadPackageDefinition(packageDefinition).index;

现在我的 index.proto 文件正在引用另一个 proto 文件 如下:

syntax = "proto3";

package index;

import public "location_updater.proto";

而我的location_updater.proto 定义如下

syntax = "proto3";

package location_updater;

service LocationUpdater{
    rpc updateLocation(Location) returns LocationUpdateResponse{}
}

message Location{
    string apiKey = 1;
    string updateTarget = 2;
    double longitude = 3;
    double latitude = 4;
}

message LocationUpdateResponse{
    int32 statusCode = 1;
}

当我执行以下操作时:

 let grpcServer = new grpc.Server();
        grpcServer.addService(indexProto.location_updater.LocationUpdater.service, {

        });

我收到一个错误TypeError: Cannot read property 'LocationUpdater' of undefined

如果我将 location_updater.proto 的内容移动到 index.proto 文件中,它可以工作,但我不希望这种行为,因为我会为不同的业务逻辑处理许多不同的 proto 文件。

我做错了什么,最好的解决方法是什么?

感谢您的期待。

【问题讨论】:

    标签: javascript node.js grpc grpc-node


    【解决方案1】:

    您需要使用includeDirs 选项在搜索路径中包含目录,以便proto loader 库知道如何查找导入的文件。这些目录应该是与import 路径相关的目录。

    在这种情况下,假设location_updater.protoindex.proto 在同一目录中,includeDirs 选项应该是一个包含单个路径__dirname/../protos 的数组。这些目录也可用于搜索主文件,因此您可以传递一个原始路径,即 index.proto

    【讨论】:

      猜你喜欢
      • 2021-11-16
      • 2018-02-10
      • 1970-01-01
      • 2022-07-05
      • 2020-08-21
      • 2019-08-21
      • 1970-01-01
      • 2023-03-24
      相关资源
      最近更新 更多