graphql和grpc之间的转换


目的

本文主要目的是将graphql转换成grpc

protoc-gen-graphql

protoc-gen-graphql插件可以让我们在写proto文件的时候加一些option,通过监听http端口实现对外暴露graphql风格的http请求。一般用于gateway层,将前端的graphql风格的请求转换成grpc

image.png

安装插件

go get github.com/ysugimoto/grpc-graphql-gateway/protoc-gen-graphql/...

代码实现

go-rpc

1.定义proto文件

// greeter.proto
syntax = "proto3";

package graphql;

option go_package = "./graphql";

import "graphql.proto";

service Greeter {
  // gRPC service information
  option (graphql.service) = {
    host: "localhost:50051"
    insecure: true
  };

  rpc SayHello (HelloRequest) returns (HelloReply) {
    // Here is plugin definition
    option (graphql.schema) = {
      type: QUERY   // declare as Query
      name: "hello" // query name
    };
  }

  rpc SayGoodbye (GoodbyeRequest) returns (GoodbyeReply) {
    // Here is plugin definition
    option (graphql.schema) = {
      type: QUERY     // declare as Query
      name: "goodbye" // query name
    };
  }
}

message HelloRequest {
  // Below line means the "name" field is required in GraphQL argument
  string name = 1 [(graphql.field) = {required: true}];
}

message HelloReply {
  string message = 1;
}

message GoodbyeRequest {
  // Below line means the "name" field is required in GraphQL argument
  string name = 1 [(graphql.field) = {required: true}];
}

message GoodbyeReply {
  string message = 1;
}

代码:greeter.proto

2.在同级目录中引入graphql需要的固定文件

graphql.proto

3.在proto文件目录中生成代码

protoc \
    -I. \
    --go_out=./rpc \
    --go-grpc_out=./rpc \
    --graphql_out=./rpc \
    greeter.proto

4.在生成的代码目录中手动写入graphql需要的固定文件

graphql.pb.go

5.运行代码

go run main.go

至此go-rpc服务已经启动

graphql-gateway

1.将go-rpc项目的proto目录直接复制过来

2.启动项目

go run main.go

至此graphql-wateway服务已启动,在控制台输入

curl -g "http://localhost:8888/graphql" -d '
{
  hello(name:"test graphql") {
    message
  }
}'

可以看到输出

{"data":{"hello":{"message":"Hello, test graphql!"}}}

总结

本文主要简单介绍了一下protoc-gen-graphql插件用法,并没有详细介绍原理,有兴趣的同学可深入研究。下面源代码可供参考:

graphql_go_rpc

graphql_gateway

参考

[1]gRPC 直接转 GraphQL

[2]grpc-graphql-gateway


文章作者: Alex
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 Alex !
  目录