How to add metadata to nodejs grpc call

浪子不回头ぞ 提交于 2019-11-29 05:58:32

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

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

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,
)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!