【问题标题】:NestJS gRPC Unimplemented Streaming Server MethodNestJS gRPC 未实现的流式服务器方法
【发布时间】:2021-09-22 12:48:30
【问题描述】:

我正在尝试使用 NestJS 和 gRPC 构建微服务。它有两个服务,第一个是gRPC服务,第二个是调用gRPC服务的REST服务。

起初,它在单一调用 findRepoById rpc 上运行良好。但它不适用于服务器流式调用findAllReposrpc。当我尝试调用findAllRepos rpc 时会抛出这样的错误

UnhandledPromiseRejectionWarning: 错误: 12 UNIMPLEMENTED: 服务器没有实现方法findAllRepos

我写的文件如下所示

// main.proto

syntax = "proto3";

import "google/protobuf/timestamp.proto";

package main;

enum Visibility {
  PUBLIC = 0;
  PRIVATE = 1;
}

message Repository {
  int32 id = 1;
  string title = 2;
  Visibility visibility = 3;
  google.protobuf.Timestamp lastSeen = 4;
}

service MainService {
  rpc findRepoById (RepoById) returns (Repository) {}
  rpc findAllRepos (NoParam) returns (stream Repository) {}
}

message RepoById {
  int32 id = 1;
}

message NoParam {}
// server.controller.ts

@Controller('repo')
export class RepoController {
  constructor(
    @Inject('RepoService') private readonly repoService: RepoService
  ) {}

  @GrpcMethod('MainService', 'findRepoById')
  findRepoById(request: RepoById, metadata: Metadata): Repository {
    const targetId = request.id;
    return this.repoService.findRepoById(targetId);
  }

  @GrpcStreamMethod('MainService', 'findAllRepos')
  findAllRepos(request: NoParam, metadata: Metadata): Observable<Repository> {
    const subject = new Subject<Repository>();

    const repositories = this.repoService.findAllRepos();
    repositories.map((repo) => {
      subject.next(repo);
    });
    subject.complete();

    return subject.asObservable();
  }
}
// client.service.ts

export class RepoGrpcService implements OnModuleInit {
  private mainService: MainServiceClient;

  constructor(@Inject('main_package') private client: ClientGrpc) {}

  onModuleInit() {
    this.mainService = this.client.getService<MainServiceClient>('MainService');
  }

  findRepoById(id: number): Observable<Repository> {
    return this.mainService.findRepoById({ id });
  }

  @GrpcStreamCall('MainService')
  findAllRepos(): Observable<Repository[]> {
    const results: Repository[] = [];

    const repoStream = this.mainService.findAllRepos({});
    repoStream.forEach((value) => console.log(value));
    repoStream.subscribe({
      next: (repo) => {
        results.push(repo);
      }
    });

    const subject = new Subject<Repository[]>();
    subject.next(results);
    subject.complete();

    return subject.asObservable();
  }
}

我想我已经遵循了与NestJS gRPC documentation 相同的所有代码,但不知何故它仍然不起作用。是不是我做错了什么?

【问题讨论】:

    标签: protocol-buffers nestjs grpc grpc-node


    【解决方案1】:

    我知道这个问题已经很久没有提出来了,但也许这个答案会对其他人有所帮助。 请注意文档,部分代码因为前面章节没有提到,所以 NestJS 不是一个例外。看来,您的问题来自控制器模块关系 再次查看文档并确保您的控制器在正确的模块中定义并且您的模块关系(导入)没有问题。

    NestJs Doc-Module

    Official Example

    【讨论】:

      猜你喜欢
      • 2021-12-10
      • 2021-08-03
      • 2019-11-09
      • 2020-05-29
      • 2021-05-14
      • 2017-05-28
      • 2020-02-08
      • 2022-11-25
      • 2020-06-18
      相关资源
      最近更新 更多