Last active
August 29, 2015 14:26
-
-
Save xinthink/5d559c5d5c6e7255bc1e to your computer and use it in GitHub Desktop.
A LeanEngine function that sends a Slack notification when the given GitHub repo got starred.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// parameters of the function | |
var repo = request.params.repo; // 'user_or_org/repo_name' | |
var slackWebhook = request.params.slackWebhook; // e.g. 'https://hooks.slack.com/services/XXX' | |
var repoUrl = 'https://api.github.com/repos/' + repo; | |
// Set the following names to match your own scheme | |
var className = 'RepoStars'; // LeanCloud class for storing repo stars | |
var fieldRepo = 'repo'; // LeanCloud field to store the repo name | |
var fieldStars = 'count'; // LeanCloud field to store the count of stars | |
var RepoStars = AV.Object.extend(className); | |
var postToSlack = function (newStars, total) { | |
console.log('posting to slack, new stars is:', newStars); | |
var msg = newStars > 0 ? ':clap:' + repo + ' got another ' + newStars + | |
' stars, to a total of ' + total + '!:+1::metal::tada:' | |
: ':broken_heart:' + repo + ' lost ' + (-newStars) + ' stars, to a total of ' + total + | |
'!:sob: work harder to win them back!:facepunch:'; | |
return AV.Cloud.httpRequest({ | |
method: 'POST', | |
url: slackWebhook, | |
headers: { | |
'Content-Type': 'application/json' | |
}, | |
body: { | |
text: msg | |
} | |
}); | |
}; | |
var onRepoStarred = function (resp) { | |
var count = resp.data.stargazers_count; | |
var theRepoStars; | |
console.log('latest stars is:', count); | |
return new AV.Query(RepoStars) | |
.equalTo(fieldRepo, repo) | |
.first() | |
.then(function (repoStars) { | |
theRepoStars = repoStars; | |
return repoStars ? repoStars.get(fieldStars) : 0; | |
}) | |
.then(function (prevCount) { | |
console.log('previous stars:', prevCount); | |
if (count !== prevCount) { | |
// got starred or unstarred, notify through Slack WebHook | |
return postToSlack(count - prevCount, count); | |
} | |
}) | |
.then(function (starsChanged) { | |
if (!starsChanged) { | |
// stars not changed, don't waste api quota | |
return; | |
} | |
// save the latest star count | |
if (!theRepoStars) { | |
theRepoStars = new RepoStars(); | |
theRepoStars.set(fieldRepo, repo); | |
} | |
theRepoStars.set(fieldStars, count); | |
return theRepoStars.save(); | |
}); | |
}; | |
AV.Cloud.httpRequest({ | |
url: repoUrl, | |
headers: { | |
'Cache-Control': 'no-cache', | |
'User-Agent': 'repo-stars-poller' | |
} | |
}) | |
.then(onRepoStarred) | |
.then(function () { | |
response.success(); | |
}) | |
.catch(function (err) { | |
response.error(err); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
LeanCloud
Starred
Unstarred