How to add metadata to nodejs grpc call

前端 未结 3 1543
醉梦人生
醉梦人生 2020-12-17 15:06

I\'d like to know how to add metadata to a nodejs grpc function call. I can use channel credentials when making the client with

var client = new proto.Docume         


        
相关标签:
3条回答
  • 2020-12-17 15:45

    You can pass metadata directly as an optional argument to a method call. So, for example, you could do this:

    var meta = new grpc.Metadata();
    meta.add('key', 'value');
    client.send(doc, meta, callback);
    
    0 讨论(0)
  • 2020-12-17 15:48

    For sake of completeness I'm going to extend on @murgatroid99 answer.

    In order to attach metadata to a message on the client you can use:

    var meta = new grpc.Metadata();
    meta.add('key', 'value');
    client.send(doc, meta, callback);
    

    On the server side int your RPC method being called, when you want to grab your data you can use:

    function(call, callback){ 
       var myVals = call.metadata.get("key"); 
       //My vals will be an array, so if you want to grab a single value:
       var myVal = myVals[0]; 
    }
    
    0 讨论(0)
  • 2020-12-17 15:52

    I eventually worked it out through introspecting the grpc credentials code and modifying the implementation to expose an inner function. In the grpc module in the node_modules, file grpc/src/node/src/credentials.js add the line

    exports.CallCredentials = CallCredentials;
    

    after CallCredentials is imported. Then, in your code, you can write something like

    var meta = grpc.Metadata();
    meta.add('key', 'value');
    var extra_creds = grpc.credentials.CallCredentials.createFromPlugin(
      function (url, callback) {
        callback(null, meta);
      }
    )
    

    Then use extra_creds in the client builder

    var creds = grpc.credentials.combineChannelCredentials(
      grpc.credentials.createSsl(),
      extra_creds,
    )
    

    Now you can make your client

    var client = new proto.Document(
      'some.address:8000',
      creds,
    )
    
    0 讨论(0)
提交回复
热议问题