Last active
October 14, 2018 18:21
-
-
Save jwbenson/a31c50af38b31865a6e1cec86f2722c8 to your computer and use it in GitHub Desktop.
gist key value store
This file contains hidden or 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
class Gist { | |
constructor(options) { | |
this.token = options.token; | |
this.gistID = options.gistID; | |
this.fileName = options.filename || 'data.json'; | |
this.description = options.description || 'unnamed stash'; | |
this.cacheData = null; | |
} | |
get(key, callback) { | |
var data = this._getCache(key); | |
if (data) { | |
return callback(null, key ? data[key] : data); | |
} | |
this._get((err, responseText, xhr) => { | |
if (err) { return callback(err); } | |
data = this._setCache(responseText); | |
callback(null, key ? data[key] : data); | |
}); | |
} | |
set(key, value, callback) { | |
this.get(null, (err, data) => { | |
data[key] = value; | |
this._set(data, (err, responseText, xhr) => { | |
if (err) { return callback(err); } | |
data = this._setCache(responseText); | |
callback(null, data); | |
}); | |
}); | |
} | |
_setCache(responseText) { | |
var json = JSON.parse(responseText); | |
this.cacheData = JSON.parse(json.files[this.fileName].content); | |
return this._getCache(); | |
} | |
_getCache() { | |
return this.cacheData; | |
} | |
_get(callback) { | |
this._ajax(`https://api.github.com/gists/${this.gistID}`, 'GET', null, callback); | |
} | |
_set(data, callback) { | |
var files = { | |
}; | |
files[this.fileName] = { | |
"content": JSON.stringify(data) | |
}; | |
this._ajax(`https://api.github.com/gists/${this.gistID}`, 'PATCH', { | |
"description": this.description, | |
"files": files | |
}, callback); | |
} | |
_create(data, callback) { | |
var files = { | |
}; | |
files[this.fileName] = { | |
"content": JSON.stringify(data) | |
}; | |
this._ajax('https://api.github.com/gists', 'POST', | |
{ | |
"description": this.description, | |
"public": false, | |
"files": files | |
}, callback); | |
} | |
_ajax(url, method, data, callback) { | |
try { | |
var xhr = new (XMLHttpRequest || ActiveXObject)('MSXML2.XMLHTTP.3.0'); | |
xhr.open(method, url, 1); | |
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); | |
xhr.setRequestHeader('Content-Type', 'application/json'); | |
xhr.setRequestHeader('Authorization', `token ${this.token}`); | |
xhr.onreadystatechange = function () { | |
if (xhr.readyState > 3) { | |
callback(null, xhr.responseText, xhr); | |
} | |
}; | |
xhr.send(JSON.stringify(data)); | |
} | |
catch (e) { | |
callback(e); | |
} | |
} | |
} | |
var gist = new Gist({ | |
token: 'TOKEN', | |
gistID: 'GISTID' | |
}); | |
gist.get(null, function (err, data) { | |
console.log(err, data); | |
}); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
example