【发布时间】:2018-04-14 08:36:38
【问题描述】:
我正在使用 Node.js 编写消息传递应用程序,我需要检测同一用户何时在一个组中发送 N 条连续消息(以避免垃圾邮件发送者)。我正在使用 bacon.js Bus push 来自所有用户的传入消息。
消息如下所示:
{
"text": "My message",
"user": { "id": 1, name: "Pep" }
}
这是我目前的工作代码:
const Bacon = require('baconjs')
const bus = new Bacon.Bus();
const CONSECUTIVE_MESSAGES = 5;
bus.slidingWindow(CONSECUTIVE_MESSAGES)
.filter((messages) => {
return messages.length === MAX_CONSECUTIVE_MESSAGES &&
_.uniqBy(messages, 'user.id').length === 1;
})
.onValue((messages) => {
console.log(`User ${__.last(messages).user.id}`);
});
// ... on every message
bus.push(message);
它创建一个滑动窗口,只保留我想要检测的连续消息的数字。在每个事件上,它过滤数组以让数据流到下一步,只有当窗口中的所有消息都属于同一个用户时。最后,在onValue中,取最后一条消息获取用户id。
对我来说,代码看起来很脏/很复杂:
-
filter在流中看起来不太自然。当 N 连续事件符合某些条件时,是否有更好的方法来发出事件? . - 有没有更好的方法在
onValue函数中只接收一个事件与用户(而不是一组消息)。 - 它并没有真正节流。如果用户在一年内发送 N 条消息,则不应检测到他或她。信息流应该以某种方式忘记旧事件。
有什么改进的方法吗?如果有帮助,我愿意将其迁移到 rxjs。
【问题讨论】:
标签: node.js reactive-programming bacon.js