无法使用@ grpc / proto-loader导入Google的原型

Olg*_*lga 4 protocol-buffers node.js grpc google-protocol-buffer grpc-node

我有以下原型:

syntax = "proto3";

import "google/rpc/status.proto";

message Response {   
    google.rpc.Status status = 1;
}

message Request {   
    Type name = 1;
}

service Service {
    rpc SomeMethod (Request) returns (Response);
}
Run Code Online (Sandbox Code Playgroud)

我在节点中编写一个客户端:

    const path = require('path');
    const grpc = require('grpc');
    const protoLoader = require('@grpc/proto-loader');
    const protoFiles = require('google-proto-files');

    const PROTO_PATH = path.join(__dirname, '/proto/myproto.proto');

    const packageDefinition = protoLoader.loadSync(
      PROTO_PATH,
      {
        keepCase: true,
        longs: String,
        enums: String,
        defaults: true,
        oneofs: true,
        includeDirs: [protoFiles('rpc')],
      },
    );

    const proto = grpc.loadPackageDefinition(packageDefinition);
    const client = new proto.Service('localhost:1111', grpc.credentials.createInsecure());
Run Code Online (Sandbox Code Playgroud)

运行客户端时,出现以下错误:TypeError:proto.Service不是构造函数。我发现它与status.proto的导入有关。使用proto-loader导入google proto的正确方法是什么?该服务器使用Java。

Max*_*lev 6

奥尔加(Olga),如果您使用includeDirs,则不能在PROTO_PATH中使用绝对路径。显然,您需要将两个路径(即myproto.proto的路径和google-proto文件的路径)放入includeDirs中,并仅使用文件名作为PROTO_PATH,然后它就可以正常工作。看这里:

https://github.com/grpc/grpc-node/issues/470

这是有效的修改后的代码。请注意,我还必须在myproto.proto中将“ Type”替换为“ int32”。

const path = require('path');
const grpc = require('grpc');
const protoLoader = require('@grpc/proto-loader');
const protoFiles = require('google-proto-files');

const PROTO_PATH = 'myproto.proto';

const packageDefinition = protoLoader.loadSync(
  PROTO_PATH,
  {
    keepCase: true,
    longs: String,
    enums: String,
    defaults: true,
    oneofs: true,
    includeDirs: ['node_modules/google-proto-files', 'proto']
    },
  );

const protoDescriptor = grpc.loadPackageDefinition(packageDefinition);
const client = new protoDescriptor.Service('localhost:1111',  grpc.credentials.createInsecure());
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你。:)