I am trying to implement a very basic stream to my web browser using grpc and express.js. However, it only ever shows the first object of the array, it does not stream the rest to the web browser. I am quite new to this, so I think I might just be overlooking something, but a hint into the right direction would be great. Thanks a lot!
Proto file
service NewsAlerts {
rpc getNewsAlerts(NewsRequest) returns (stream NewsResponse) {}
}
message NewsRequest{
}
message NewsResponse{
string category = 1;
string url = 2;
}
app.js (server-side)
var news = [{category: "Weather alert", url: "URL 1"},{category: "System update",url: "URL 2"},{category: "Current news",url: "URL 3"},{category: "Privacy & Legal",url: "URL 4"},{category: "Statistics",url: "URL 5"}]
function getNewsAlerts(call, callback) {
for(var i = 0; i < news.length; i++){
call.write({
category: news[i].category,
url: news[i].url,
});
}
call.end()
}
index.js (client-side)
router.get('/news', function(req, res, next) {
var call = client.getNewsAlerts({});
call.on('data', function(response){
res.render('news', {category:response.category, url:response.url});
});
call.on('end', function(){
});
call.on('error', function(e){
console.log(e);
})
});
news.ejs (client-side)
<div id="text-part">
<%= category %>
<%= url%>
</div>
Would you be able to detect why it is not streaming and only sending the first value of the array on the web browser? Thanks a lot
-I tried to pass in the array directly via call.write(), but this would just show an output of [Object, object] into the web browser. -I also tried to use JSON.stringify() on the [Object, object] array, but same outcome. -I am very new to this, so I might have a logic mistake on how to use res.render here, but any insights is appreciated.
In the end the strings within the array should stream on the web browser, but I cannot make it work, after the first value is passed, the call seems to end. Thanks a lot for the help!
I was able to fix it, I simply pushed the data into an array within index.js and then rendered the array.
Updated code for reference:
Index.js
router.get('/news', function(req, res, next) {
var call = client.getNewsAlerts({});
var newsItems = [];
call.on('data', function(response){
newsItems.push({category: response.category, url:response.url});
});
call.on('end', function(){
res.render('news', {newsItems:newsItems});
});
call.on('error', function(e){
console.log(e);
})
});
news.ejs
<div id="text-part">
<% newsItems.forEach(function(item) { %>
<%= item.category %>
<%= item.url %>
<% }); %>
</div>