Skip to content

Instantly share code, notes, and snippets.

@jwbenson
Last active October 14, 2018 18:21
Show Gist options
  • Save jwbenson/a31c50af38b31865a6e1cec86f2722c8 to your computer and use it in GitHub Desktop.
Save jwbenson/a31c50af38b31865a6e1cec86f2722c8 to your computer and use it in GitHub Desktop.
gist key value store
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);
});
@jwbenson
Copy link
Author

jwbenson commented Oct 19, 2017

example

var gist = new Gist({
	token: 'YOUR TOKEN',
	gistID: 'GIST ID',
        filename: 'test.json',
        description: 'some stash name'
});

gist.set('test', '123', function (err, data) {
    gist.get('test', function (err, data) {
        console.log(data); //'123'
    });
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment