[英]How to get metadata from a gRPC service method in Node
I have a gRPC service running like this:我有一个像这样运行的 gRPC 服务:
server.addService(PassportService, implementation);
server.bind(mfeConfig().grpc.passport, grpc.ServerCredentials.createInsecure());
server.start();
I can call my service from a client like this:我可以像这样从客户端调用我的服务:
const request = new GetConsoleUserRequest();
const meta = new grpc.Metadata();
meta.add('__.grpc.exchanged-token', token);
this.client.getConsoleUser(
request,
meta,
(err: grpc.ServiceError, val: GetConsoleUserResponse) => {
But I can't figure out how to read the metadata in my service implementation.但是我不知道如何在我的服务实现中读取元数据。 Now matter which overloads I define for
getConsoleUser
, the metadata is never one of the arguments.现在无论我为
getConsoleUser
定义了哪些重载,元数据都不是参数之一。 Here's getConsoleUser
, which just returns some fake data:这是
getConsoleUser
, getConsoleUser
返回一些假数据:
getConsoleUser: (_req: GetConsoleUserRequest, callback: Function) => {
const response = new GetConsoleUserResponse();
const user = new ConsoleUser();
user.setName('Bob Loblaw');
// Change me to userStatus.GUEST to simulate anonymous user access
user.setState(userStatus.REGISTERED);
user.setEmail('bob@loblaw.com');
response.setConsoleUser(user);
callback(null, response);
},
I've tried changing that signature to this:我试过将该签名更改为:
getConsoleUser: (_req: GetConsoleUserRequest, meta: grpc.Metadata, callback: Function) => {
But if I do that, the second argument is actually the callback function, and the third argument is undefined.但是如果我这样做,第二个参数实际上是回调函数,而第三个参数是未定义的。
Is there a way to read the metadata from my service implementation?有没有办法从我的服务实现中读取元数据? Or is there some other class that I have to attach my service to so that I can listen for incoming metadata?
还是我必须将服务附加到其他一些类,以便我可以侦听传入的元数据?
The first argument passed to the server method is not a message object.传递给服务器方法的第一个参数不是消息对象。 It is a "call" object that has multiple different properties, including
call.metadata
to get the metadata, and for unary and server streaming methods, call.request
has the actual request message.它是一个具有多个不同属性的“调用”对象,包括用于获取元数据的
call.metadata
,对于一元和服务器流方法, call.request
具有实际的请求消息。 For streaming requests the call object is also a Node.js Stream object that you can write to and/or read from, whichever is relevant.对于流请求, call 对象也是一个 Node.js Stream 对象,您可以写入和/或从中读取,以相关的为准。
For more details, look at the ServerUnaryCall
and Server(Readable|Writable|Duplex)Stream
classes in the API reference documentation .有关更多详细信息,请查看API 参考文档中的
ServerUnaryCall
和Server(Readable|Writable|Duplex)Stream
类。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.