【问题标题】:Converting Go gRPC call to Node.js将 Go gRPC 调用转换为 Node.js
【发布时间】:2022-01-23 13:49:05
【问题描述】:

有一个函数使用 grpc 调用从 grpc 节点获取某些数据。

func GetVotesByAddr(r *http.Request, cli iotexapi.APIServiceClient) (proto.Message, error) {
    method := &iotexapi.ReadStakingDataMethod{
        Method: iotexapi.ReadStakingDataMethod_BUCKETS_BY_VOTER,
    }
    methodData, err := proto.Marshal(method)
    if err != nil {
        return nil, err
    }
    vars := mux.Vars(r)
    readStakingdataRequest := &iotexapi.ReadStakingDataRequest{
        Request: &iotexapi.ReadStakingDataRequest_BucketsByVoter{
            BucketsByVoter: &iotexapi.ReadStakingDataRequest_VoteBucketsByVoter{
                VoterAddress: vars["addr"],
                Pagination: &iotexapi.PaginationParam{
                    Offset: uint32(0),
                    Limit:  uint32(1000),
                },
            },
        },
    }
    requestData, err := proto.Marshal(readStakingdataRequest)
    if err != nil {
        return nil, err
    }
    request := &iotexapi.ReadStateRequest{
        ProtocolID: []byte("staking"),
        MethodName: methodData,
        Arguments:  [][]byte{requestData},
    }

    response, err := cli.ReadState(context.Background(), request)
    if err != nil {
        return nil, err
    }

    bucketlist := &iotextypes.VoteBucketList{}
    if err := proto.Unmarshal(response.Data, bucketlist); err != nil {
        return nil, err
    }
    return bucketlist, nil
}

代码取自https://github.com/iotexproject/pharos/blob/master/handler/handler_votes.go

我需要将其转换为 js,我正在使用这个库 https://docs.iotex.io/native-development/reference-code/call-any-rpc-method,它支持使用 js 进行 ioTex 网络的 rpc 调用。

const state = await antenna.iotx.readState({
    protocolID: "",
    methodName: "",
    arguments: "",
});

RPC调用文档https://docs.iotex.io/reference/node-core-api-grpc#readstate

任何关于我们如何重建从 GO 到 Node.js 的调用的帮助都会有所帮助。

【问题讨论】:

    标签: javascript node.js go grpc


    【解决方案1】:

    好吧,玩了一会儿我自己解决了这个问题,下面是代码供以后参考

    const state = await antenna.iotx.readState({
      protocolID: Buffer.from("staking"),
      methodName: IReadStakingDataMethodToBuffer({
        method: IReadStakingDataMethodName.BUCKETS_BY_VOTER,
      }),
      arguments: [
        IReadStakingDataRequestToBuffer({
          bucketsByVoter: {
            voterAddress: ioAddress,
            pagination: {
              offset: 0,
              limit: 1000,
            },
          },
        }),
      ],
      height: undefined,
    });
    

    【讨论】:

    • 一般情况下,gRPC 最好的方式是拥有相应的 protobuf 文件,并使用 protoc 命令生成您需要的客户端或服务器。有一个 JS 生成器。这是你在这里用的吗?
    猜你喜欢
    • 2019-07-14
    • 1970-01-01
    • 1970-01-01
    • 2020-04-02
    • 2017-04-10
    • 2019-02-20
    • 2015-12-30
    • 2019-03-19
    • 2018-08-16
    相关资源
    最近更新 更多