javascript - 为事件处理程序编写中间件

标签 javascript node.js typescript

用例:

我必须处理几个需要“可用客户端”的事件。所以在每个事件处理程序中,我首先必须尝试获取可用的客户端。如果没有可用的客户端,我将回复一条“服务不可用”消息。现在我已经实现了这样的要求:

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/

相关文章:

javascript - 在输入字段中选择一些文本,但不是全部,当它获得焦点时

node.js - Reactjs错误,对象作为react子对象无效?

mysql - 在 Node.js 中处理查询的偏移量或限制

javascript - 更新函数 javascript 和 mongodb

Typescript:空检查在 array.map 函数内不起作用

javascript - Ionic/Angular HttpClient 未获取类型数据 : error Property 'name' does not exist on type '{}'

javascript - IE8 小书签 : Cannot drag to bookmark bar

javascript - 为不同的 WordPress 页面添加自定义样式表

javascript - 从 chrome 扩展程序传递大 blob 或文件

javascript - 当数组中的函数之一不返回 Promise 时,我可以使用 $q.all 吗?