How to add metadata to nodejs grpc call

2019-02-12 08:13发布

问题:

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.Document('some.address:8000',
    grpc.credentials.createInsecure()
)

Which are send when using client.Send(doc, callback), but the go grpc server looks in the call metadata for identification information which I have to set. I tried using grpc.credentials.combineChannelCredentials with the insecure connection and a grpc.Metadata instance but I can't find the right way to do it.

The error I run into is TypeError: compose's first argument must be a CallCredentials object. I tried to follow it down but it goes into c code which loses me, I can't see what javascript type I have to give to comebineChannelCredentials to achieve what I'm looking for and the docs are a little sparse on how to achieve this.

回答1:

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);


回答2:

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]; 
}


回答3:

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,
)