Created
September 23, 2017 19:35
-
-
Save fletcherist/48dd09299fdbd87fa480f8032c5a2ff1 to your computer and use it in GitHub Desktop.
greengit-lambda
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
const GitHubApi = require('github') | |
const github = new GitHubApi({ | |
version: '3.0.0', | |
debug: false, | |
protocol: 'https', | |
host: 'api.github.com', | |
pathPrefix: '', | |
timeout: 5000, | |
headers: { | |
'user-agent': 'GitHub Commits Abuser' // GitHub is happy with a unique user agent | |
} | |
}) | |
github.authenticate({ | |
type: 'token', | |
token: 'YOUR GITHUB AUTH TOKEN' | |
}) | |
const commitIntoStreak = shaKey => { | |
var rand = Math.floor(Math.random() * 1488) | |
const content = new Buffer(`${rand} days of endless commiting and counting..`).toString('base64') | |
return github.repos.updateFile({ | |
owner: 'fletcherist', | |
repo: 'greengit-repo', | |
path: 'streak.md', | |
message: 'streak update', | |
sha: shaKey, | |
content: content | |
}) | |
} | |
const ONE_DAY = 432e5 | |
const ONE_HOUR = 36e5 | |
// global variable to save | |
let LAST_COMMITED_TIME = Date.now() | |
const IS_READY_TIMEOUT = ONE_DAY | |
const isReadyComparator = initialTime => Date.now() - initialTime > IS_READY_TIMEOUT | |
const getReadyTime = () => IS_READY_TIMEOUT - (Date.now() - LAST_COMMITED_TIME) | |
const convertReadyTimeIntoHours = readyTime => (readyTime / ONE_HOUR).toPrecision(4) | |
const isReadyForCommiting = ((initialTime = Date.now()) => { | |
return () => { | |
const isReady = isReadyComparator(initialTime) | |
isReady ? initialTime = Date.now() : null | |
LAST_COMMITED_TIME = initialTime | |
return isReady | |
} | |
})() | |
const getGithubSha = () => new Promise(resolve => { | |
github.repos.getContent({ | |
owner: 'fletcherist', | |
repo: 'greengit-repo', | |
path: 'streak.md' | |
}).then(res => resolve(res.data.sha)) | |
}) | |
exports.greengit = (req, res) => { | |
if (!isReadyForCommiting()) { | |
return res.send(`Not ready for commiting yet. | |
Left ${convertReadyTimeIntoHours(getReadyTime())} hours`) | |
} | |
getGithubSha() | |
.then(commitIntoStreak) | |
.then(() => { | |
console.log('Commited successfully!') | |
return res.send('Commited successfully!') | |
}) | |
.catch(error => res.send(error)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment