サーバーの実装 (Node.js & TypeScript)
import { sendUnaryData, Server, ServerCredentials, ServerUnaryCall } from "@grpc/grpc-js";
import { ChargeRequest, Payment } from "./minifinancier_pb"; // メッセージ定義から自動生成されたコード
import { PaymentGatewayService } from "./minifinancier_grpc_pb"; // サービス定義から自動生成されたコード
import { Timestamp } from "google-protobuf/google/protobuf/timestamp_pb";
function charge(call: ServerUnaryCall, callback: sendUnaryData) {
const response = new Payment()
.setId("payment-42") // 説明のため決め打ち
.setUserId(call.request.getUserId())
.setAmount(call.request.getAmount())
.setCreateTime(Timestamp.fromDate(new Date()));
callback(null, response); // コールバックの第2引数に rpc の返り値を渡す(第
1引数に値を渡すのはエラーの場合)
}
const server = new Server();
server.addService(PaymentGatewayService, { charge }); // サービスと対応する rpc charge の実装をサーバーに追加
server.bindAsync("0.0.0.0:50051", ServerCredentials.createInsecure(), () => {
server.start(); // 50051 ポートで gRPC サーバーを起動
});