grpc-webを使って.protoファイルからWEBブラウザ用JSコードを自動生成する


こんな人向け

  • gRPCの基礎知識は押さえてる
  • WEBフロントエンドからgRPCサービスにアクセスしたい
  • .protoファイルからWEBフロントエンド用のJSコードを自動生成したい
  • Mac使ってる(他OSの方はそれぞれ読み替えてご覧ください)

用語

grpc-web

WEBブラウザからgRPCサービスにアクセスするためのJavaScriptライブラリ。

protoc-gen-grpc-web

grpc-web公式のprotocプラグイン。
WEBブラウザ用のJavaScriptコードを自動生成してくれる。

コード生成手順

Protocol Bufferインストール

protoc というコマンドを使うのでprotobufをインストール

brew install protobuf
protoc --version

protoc-gen-grpc-webインストール

下記ページ内にある protoc-gen-grpc-web-1.0.3-darwin-x86_64 って感じのファイルをダウンロードする(Macはdarwin)
https://github.com/grpc/grpc-web/releases

ダウンロード後、そのファイルパスを下記コマンドに入れて実行

sudo mv ~/Downloads/protoc-gen-grpc-web-1.0.3-darwin-x86_64 /usr/local/bin/protoc-gen-grpc-web
chmod +x /usr/local/bin/protoc-gen-grpc-web

protoファイルを作る

helloworld.proto
syntax = "proto3";
package helloworld;
service Greeter {
  rpc SayHello (HelloRequest) returns (HelloReply);
}
message HelloRequest {
  string name = 1;
}
message HelloReply {
  string message = 1;
}

コード生成コマンド実行

下記を実行すると2つのJSファイルが生成される

protoc -I=./ helloworld.proto \
--js_out=import_style=commonjs:./ \
--grpc-web_out=import_style=commonjs,mode=grpcwebtext:./
  • helloworld_grpc_web_pb.js
  • helloworld_pb.js

生成されたJSの扱い方

index.js
import helloworld from './helloworld_grpc_web_pb'

const greeter = new helloworld.GreeterPromiseClient('http://localhost:50051')
const req = new helloworld.HelloRequest()
req.setName('World')
greeter
  .sayHello(req)
  .then((res)=>console.log(res))
  .catch((err)=>console.error(err))

実際に動かしてみる

otanuさんという方が作られたこちらのサンプルが非常に分かりやすいので、実際に動かして試してみたいという方は是非。(丸投げですいません...!)
https://github.com/otanu/hello-grpc-web

参考文献

下記ページを参考にさせていただきました。
先人の皆様へ感謝。ありがとうございます。

https://qiita.com/otanu/items/98d553d4b685a8419952
https://developers.google.com/protocol-buffers/docs/reference/javascript-generated
https://github.com/grpc/grpc-web
https://qiita.com/keitarou/items/487972af127d8b720d4b
http://blog.64p.org/entry/2018/10/31/141431
http://terachanple.hatenablog.jp/entry/2018/11/01/214855