GRPC with GraphQL and TypeScript

gRPC 和 GraphQL 都是 2015 年推出的接口设计方案,各有各的优势。

GraphQL 在提供了 GraphQL schema stitching 以支持微服务架构。 但是,由于 GraphQL 请求被解析了两次,所以可能导致性能瓶颈。

所以,APP 与独立的 GraphQL Server 集群进行通信,而 GraphQL Server 通过 gRPC 与微服务应用进行通信是一个不错的方案。

  • GraphQL Server 作为唯一的 BFF(Backend for Frontend) 入口。

  • gRPC Server,以执行所有功能操作。

这两类微服务托管在 K8S(Kubernetes) 上,因此还需要在 gRPC 中实现运行状况检查机制。

技术选型参考

For GraphQL Server:

The difference between grpc and @grpc/grpc-js see there

如果你的应用还作为 gRPC Server:

gRPC 直接转 GraphQL

存在一些现成的轮子做了 gRPC 直接转 GraphQL 的工作。

生成 TypeScript 声明文件

gRPC、GraphQL 以及 TypeScript 都做了类型声明的工作,需要以某种方式做映射,尽可能保证类型统一易于维护。

基于 proto files 生成 Typescript 类型

可以使用以下工具基于 proto files 直接生成 TypeScript 声明文件

基于 GraphQL Schema 生成 Typescript 类型

可以使用以下工具基于 GraphQL Schema 直接生成 TypeScript 声明文件

如果 GraphQL Schema 是基于 proto files 生成的,那么推荐的流程应该是:

  1. proto files to GraphQL Schema

  2. proto files to client and TS types.

  3. GraphQL Schema to TS types.

Reference

最后更新于