0

我需要通过 Envoy 将 JSON 作为请求发送到 grpc API。目前,我正在使用来自 protoc 自动生成的代码的 setter 函数。有没有办法直接将 json(甚至是深层嵌套的)转换为 proto 消息并将其作为请求发送?

这是原型文件。

syntax = "proto3";

package movieDetails;

message Category {
    string code = 1;
    repeated float ratings = 2;
    bool liked = 3;
}

message MovieRequest {
    string ping = 1;
    Category sample = 2;
}

message MovieResponse {
    string title = 1;
    string desc = 2;
    repeated int32 numbers = 3;
    repeated Category sample = 4;
}

service MovieDetailService {
    rpc getDetails(MovieRequest) returns (MovieResponse);
}

我使用 protoc 自动生成 *_pb.js 文件。

原型消息是指这种格式的数据。

{
  "wrappers_": {
    "2": {
      "wrappers_": null,
      "arrayIndexOffset_": -1,
      "array": [
        "XY",
        [
          0.1,
          0.6,
          0.9
        ],
        true
      ],
      "pivot_": 1.7976931348623157e+308,
      "convertedPrimitiveFields_": {
        "2": true
      }
    }
  },
  "arrayIndexOffset_": -1,
  "array": [
    "Mission Impossible",
    [
      "XY",
      [
        0.1,
        0.6,
        0.9
      ],
      true
    ]
  ],
  "pivot_": 1.7976931348623157e+308,
  "convertedPrimitiveFields_": {}
}

对应的 JSON

{
  "ping": "Mission Impossible",
  "sample": {
    "code": "XY",
    "ratingsList": [
      0.1,
      0.6,
      0.9
    ],
    "liked": true
  }
}

这是我的反应代码。

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';

const { MovieDetailServiceClient } = require('./grpc/sample_grpc_web_pb');
const { MovieRequest, serializeBinaryToWriter , Category } = require('./grpc/sample_pb');

var client = new MovieDetailServiceClient('http://localhost:9090', null, null);
console.log(client)
class App extends Component {
   callGrpcService = async () => {
    const request = new MovieRequest();
    request.setPing('Mission Impossible');

    const cat = new Category();
    cat.setCode('XY')
    cat.setRatingsList([0.1, 0.6, 0.9])
    cat.setLiked(true)


    const catJson = {code: 'XY', ratings: [0.1, 0.4], liked: false}
    console.log(catJson)// CAN THIS BE DIRECTLY ENCODED AND SEND REQUEST??

    await request.setSample(cat)
    console.log(':', request.toObject())
    client.getDetails(request, {}, (err, response) => {
      if (response == null) {
        console.log('BUG:',err)
      }else {
        console.log(response.getTitle(), response.getDesc(), response.getNumbersList(), response.getSampleList())
        console.log(response.toObject())
        console.log(response.getSampleList().map(it => it.getRatingsList()))
      }
    });
  }

  render() {
    return (
      <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <button style={{padding:10}} onClick={this.callGrpcService}>Click for grpc request</button>
        </header>
      </div>
    );
  }
}

export default App;
4

0 回答 0