Last active
August 10, 2016 17:27
-
-
Save nucleartide/e95900c673fab9d42766f7e41240890e to your computer and use it in GitHub Desktop.
Slots Data Tool Simulator (aka concurrent GitHub file updating)
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 co = require('co') | |
const request = require('superagent') | |
const atob = require('atob') | |
const btoa = require('btoa') | |
const sleep = require('co-sleep') | |
const token = process.env.TOKEN | |
if (!token) throw new Error('need token') | |
function updateJson(id, poll) { | |
return function*(){ | |
let res = yield request | |
.get('https://api.github.com/repos/RisingTideGames/slots-live-data-dev/contents/test.json') | |
.set('Authorization', `token ${token}`) | |
.then(res => res.body) | |
let json = JSON.parse(atob(res.content)) | |
let reqs = 0 | |
while (true) { | |
json.id = Date.now() | |
res = yield request | |
.put('https://api.github.com/repos/RisingTideGames/slots-live-data-dev/contents/test.json') | |
.set('Authorization', `token ${token}`) | |
.send({ | |
message: `current time: ${json.id}`, | |
content: btoa(JSON.stringify(json, null, 4) + '\n'), | |
sha: res.sha, | |
}) | |
.then(res => res.body.content) | |
reqs++ | |
console.log(`[${id}]: committed ${reqs} times:`, JSON.stringify(json)) | |
yield sleep(poll) | |
} | |
} | |
} | |
function spawn1() { | |
co(updateJson(1, 10 * 1000)).catch(respawn1) | |
} | |
function respawn1(err) { | |
console.error('coroutine 1:', err.stack) | |
spawn1() | |
} | |
function spawn2() { | |
co(updateJson(2, 5 * 1000)).catch(respawn2) | |
} | |
function respawn2(err) { | |
console.error('coroutine 2:', err.stack) | |
spawn2() | |
} | |
co(function*(){ | |
spawn1() | |
yield sleep(2.5 * 1000) | |
spawn2() | |
}).catch(err => console.error(err.stack)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment