用例:
我必须处理几个需要“可用客户端”的事件。所以在每个事件处理程序中,我首先必须尝试获取可用的客户端。如果没有可用的客户端,我将回复一条“服务不可用”消息。现在我已经实现了这样的要求:
public constructor(consumer: RpcConsumer) {
consumer.on('requestA', this.onRequestA);
}
private onRequestA = async (msg: RpcConsumerMessage) {
const client: RequestClient = this.getClient(msg);
if (client == null) {
return;
}
msg.reply(await client.getResponseA());
}
private getClient(msg: RpcConsumerMessage): RequestClient {
const client: RequestClient= this.clientManager.getClient();
if (client == null) {
const err: Error = new Error('Currently there is no client available to process this request');
msg.reply(undefined, MessageStatus.ServiceUnavailable, err);
return;
}
return client;
}
问题:
我不想一次又一次地检查所有事件处理程序中的可用客户端。相反,我认为中间件非常适合这个用例。它会检查可用的客户端并传递客户端实例(如果有的话)。如果没有可用的客户端,它将以错误消息作为响应。
问题:
我将如何为这种情况编写这样的中间件?
最佳答案
为此构建一个柯里化(Currying)方法:
private withClient(cb: (client: RequestClient) => string | Promise<string>) {
return function(msg: RpcConsumerMessage) {
const client: RequestClient= this.clientManager.getClient();
if (client == null) {
const err: Error = new Error('Currently there is no client available to process this request');
msg.reply(undefined, MessageStatus.ServiceUnavailable, err);
return;
}
msq.reply(await cb(client));
};
}
因此您可以将其用作:
private onRequestA = withClient(client => client.getResponseA());
关于javascript - 为事件处理程序编写中间件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50085983/