상세 컨텐츠

본문 제목

PART 2 - How To Get Data from gRPC-Web Server using the Prot - REACT

본문

This article describes how to comunicate with a gRPC-Web proxy server with the Protobuf compilation files we created from the Part 1.
 

반응형

Part 1:
https://ranku.tistory.com/161

 

React & gRPC-Web : PART 1 - How To Compile Protobuf in Windows Environment

This article discusses how to compile gRPC-Web's Protobuf file for React (or other JavaScript-based web app) in Windows environment. Thi is only front-end side. The backend must be setup as gRPC-Web server using .NET gRPC service with gRPC-Web or Envoy pro

ranku.tistory.com


1. Prerequisites 

a. React Project and Protobuf files

This article will utilize the following files. They are all located in src/protos folder.  Your case may be different.

  • greet.proto
  • greet_grpc_web_pb.js
  • greet_pb.js

b. gRPC-Web Server or Proxy

Make sure you have a gRPC-Web server or Proxy ready and reachable from your frontend app.  If not accessible, please review CORS settings on your server or proxy.
 

728x90

2. Code Explained

This example will create hello.jsx file.

a. Define State Variable, Client, Service Request, and Service Response 

// gRPC-Web Client, its service request and reply
const { GreeterClient } = require('../protos/greet_grpc_web_pb');
const { HelloRequest, HelloReply } = require('../protos/greet_pb.js');

//State Variable
const { retValue, setRetValue } = useState('');

The words showing inside { } for the client, service request and reply definitions are retrieved from the .js compilation files (see examples below).  They are not set up arbitrarily.  


greet_grpc_web_pb.js
Definition of GreeterClient

proto.greet.GreeterClient =
    function(hostname, credentials, options) {
  if (!options) options = {};
  options.format = 'text';

  /**
   * @private @const {!grpc.web.GrpcWebClientBase} The client
   */
  this.client_ = new grpc.web.GrpcWebClientBase(options);

  /**
   * @private @const {string} The hostname
   */
  this.hostname_ = hostname.replace(/\/+$/, '');

};

greet_pb.js
Definition of HelloRequest & HellpReply

proto.greet.HelloRequest = function(opt_data) {
  jspb.Message.initialize(this, opt_data, 0, -1, null, null);
};

proto.greet.HelloReply = function(opt_data) {
  jspb.Message.initialize(this, opt_data, 0, -1, null, null);
};

b. Initiate GreeterClient

let client = new GreeterClient('URL of your gRPC-Web server or proxy', null, null);

 

 

c. Define a Service-Calling Constant or Function

The request has one parameter called "name".  We are setting the parameter using setName.  This example will update the state varaiable retValue with the returned value from the service.

const callGrpcService = () => {
    const request = new HelloRequest();
    request.setName('Frank'); // setName is explained below

    client.sayHello(request, {"Access-Control-Allow-Origin": "*"}, (err, response) => {
        if (response == null) {
            setReturnVal(err);
        } else {
            setReturnVal(response.getMessage()); // getMessage is explained below
        }
    });
};

How did we know to use "setName" or "getMessage"?  Those are defined in greet_pb.js file as below.

proto.greet.HelloRequest.prototype.setName = function(value) {
  return jspb.Message.setProto3StringField(this, 1, value);
};

proto.greet.HelloReply.prototype.getMessage = function() {
  return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, ""));
};

 

d. In the Page Component (hello.jsx)

The example below adds a h1 and a button element. The click event of the button will call the gRPC-Web service using the client and it will update the state variable retValue, which will then update h1 tag.

return (
    <div>
        <h1 id="txtTitle">{retValue}</h1>
        <button style={{padding:10}} onClick={callGrpcService}>Click for grpc request</button>
    </div>
)

Below is the complete code for hello.jsx component:

import React, { Component, useState } from 'react';

export default function Hello() {
    const { retValue, setRetValue } = useState('');
    
    const { GreeterClient } = require('../protos/greet_grpc_web_pb');
    const { HelloRequest, HelloReply } = require('../protos/greet_pb.js');
    
    var client = new GreeterClient('URL of gRPC-Web server or proxy', null, null);

    const callGrpcService = () => {
        const request = new HelloRequest();
        // SETS A REQUEST PARAMETER
        request.setName('Frank');

        client.sayHello(request, {"Access-Control-Allow-Origin": "*"}, (err, response) => {
            if (response == null) {
                setRetValue(err);
            } else {
                setRetValue(response.getMessage());
            }
        });
    };

    return (
        <div>
            <h1 id="txtTitle">{retValue}</h1>
            <button style={{padding:10}} onClick={callGrpcService}>Click for grpc request</button>
        </div>
    )
}

 

728x90
반응형

관련글 더보기