I am making a newsreader app and using Parse.com background jobs to collect links from RSS feed of the newspaper. I have used xmlreader.js and sax.js to parse the httpResponse and using saveAll and beforeSave, periodically update the classes in data browser.
I have multiple newspapers with multiple categories making a total of more than 30 pairs, (I would have to later include more pair as I would like to include regional newspapers). Till now I was working with one newspaper and one category - The Hindu, sports category; and it is now working fine. Making copies of these two function and create jobs wont be efficient I think.
Therefore, I wanted to ask if I can convert both these jobs and beforeSave into some kind of function so that I can just pass in either newspaper-category pair class name or its url to do the stuff automatically.
Full Code - main.js
job -
Parse.Cloud.job("job_hindu_sports", function (request, response) {
return Parse.Cloud.httpRequest({
url: 'http://www.thehindu.com/sport/?service=rss'
}).then(function(httpResponse) {
var someXml = httpResponse.text;
xmlreader.read(someXml, function (err, res){
if(err) {
response.error("Error " +err);
return console.log(err);
}
var listArray = [];
res.rss.channel.item.each(function (i, item){
var hinduSports = new HinduSports(); //@startswithaj - this part
hinduSports.set("link", item.link.text());
hinduSports.set("title", item.title.text());
hinduSports.set("pubDate", item.pubDate.text());
//console.log("pubDate - "+ item.pubDate.text());
listArray.push(hinduSports);
});
var promises = [];
Parse.Object.saveAll(listArray, {
success: function(objs) {
promises.push(objs);
console.log("SAVED ALL!");
},
error: function(error) {
console.log("ERROR WHILE SAVING - "+error);
}
});
return Parse.Promise.when(promises);
});
}).then(function() {
response.success("Saving completed successfully.");
},function(error) {
response.error("Uh oh, something went wrong.");
});
});
beforeSave -
Parse.Cloud.beforeSave("HinduSports", function(request, response) {
//console.log("in beforeSave");
var query = new Parse.Query(HinduSports);
var linkText = request.object.get("link")
var titleText = request.object.get("title");
query.equalTo("link", linkText);
query.first({
success: function(object) {
//console.log("in query");
if (object) {
//console.log("found");
if(object.get('title')!==titleText){
console.log("title not same");
object.set("title", titleText);
response.success();
}
else{
console.log("title same");
response.error();
}
} else {
console.log("not found");
response.success();
}
},
error: function(error) {
response.error();
}
});
});