我的总体目标是观察我的数据库是否有任何更改,并自动将这些更改广播给连接到我网站的任何用户。我看到的问题是我有一个动作触发了对我的数据库的发布请求,然后同时触发了事件流,因为我正在观看的模型已经改变。这导致初始操作完成,并且由事件流触发的操作在完成之前被中断。
这是为在我的数据库中创建新的博客文章条目而触发的第一个操作
export const topicSubmit = (date, newTopic, newTopicBody, memberId, name) => {
return {
type: 'TOPIC_SUBMIT',
payload: axios({
method: 'post',
url: `/api/blogPosts`,
data: {
"blogTitle": newTopic,
"blogBody": newTopicBody,
"date": date,
"upVotes": 0,
"numComments": 0,
"voteNames": [],
"memberId": memberId,
"steamNameId": name
}
})
.then(response => {
return response.data
})
.catch(err => err)
}
}
// this is the boot script that creates the change stream
var es = require('event-stream');
module.exports = function (app) {
console.log('realtime boot script')
var BlogPost = app.models.BlogPost;
BlogPost.createChangeStream(function (err, changes) {
changes.pipe(es.stringify()).pipe(process.stdout);
});
}
// this is the event listener on my front end that will dispatch all
// changes made in my database to my front end
componentDidMount() {
const { dispatch } = this.props;
let urlToChangeStream = '/api/blogPosts/change-stream?_format=event-stream';
let src = new EventSource(urlToChangeStream);
src.addEventListener('data', function (msg) {
let data = JSON.parse(msg.data);
dispatch(liveChangeBlogs(data))
});
我期望在事件侦听器调度“liveChangeBlogs”操作之前,“TOPIC_SUBMIT”操作应该返回完成这是我在环回事件流https://loopback.io/doc/en/lb3/Realtime上找到的文档-server-sent-events.html