LoginSignup
1
0

More than 1 year has passed since last update.

Node.js環境でgrpc-webを動かす

Last updated at Posted at 2021-08-28

@improbable-eng/grpc-webはNode.jsサポートしている。

前回のgrpcエンドポイントにアクセスできるnode.jsプロジェクトを作ることを目標とする。

最終的なプロジェクト構成

スクリーンショット 2021-08-28 22.34.27.png

必要なパッケージのinstall

@improbable-eng/grpc-web-node-http-transportが必要。

npm install @improbable-eng/grpc-web @improbable-eng/grpc-web-node-http-transport ts-protoc-gen

.protoファイルの設置

proto/cat.protoを作成

cat.proto
syntax = "proto3";

// option go_package = "cat/;pb";

option go_package = "./;pb";

package cat;

service Cat {
    rpc GetMyCat (GetMyCatMessage) returns (MyCatResponse) {}
}

message GetMyCatMessage {
    string target_cat = 1;
}

message MyCatResponse {
    string name = 1;
    string kind = 2;
}

コードの自動生成

protoc.shを用意し実行する。

protoc.sh
protoc -I. \
    --plugin="protoc-gen-ts=./node_modules/.bin/protoc-gen-ts" \
    --js_out="import_style=commonjs,binary:./" \
    --ts_out="service=grpc-web:./" \
    ./proto/cat.proto

クライアントコード作成

index.js
const { GetMyCatMessage } = require("./proto/cat_pb");
const { CatClient } = require("./proto/cat_pb_service");
const {
  NodeHttpTransport,
} = require("@improbable-eng/grpc-web-node-http-transport");

const client = new CatClient("http://127.0.0.1:9000", {
  transport: NodeHttpTransport(), // これが必須
});

const request = new GetMyCatMessage();
request.setTargetCat("tama");
client.getMyCat(request, {}, (err, response) => {
  if (response == null) {
    console.log(err);
  } else {
    console.log(response);
  }
});

第二引数のmetadataはなくてもいい。

client.getMyCat(request, (err, response) => {
  if (response == null) {
    console.log(err);
  } else {
    console.log(response);
  }
});

実行

$ node index.js 
{
  wrappers_: null,
  messageId_: undefined,
  arrayIndexOffset_: -1,
  array: [ 'tama', 'mainecoon' ],
  pivot_: 1.7976931348623157e+308,
  convertedPrimitiveFields_: {}
}
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0