Skip to content

Commit

Permalink
first commit
Browse files Browse the repository at this point in the history
  • Loading branch information
LouisT committed Apr 28, 2012
0 parents commit f0a7c16
Show file tree
Hide file tree
Showing 8 changed files with 381 additions and 0 deletions.
39 changes: 39 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
GistDB
======

I will write a better readme later.

This project was started just to learn the gist api.

This project is [Unlicensed]http://unlicense.org/

Commands
--------
I will make this better, for now look at the examples.

Example
-------
var GistDB = require('gistdb');
gdb = new GistDB('USERNAME','PASSWORD');
content = {example:'This is an example database!'};
gdb.create(content,'example.db');
gdb.on('created',function (data) {
console.log('New database created! ('+data.id+')');
init(gdb);
});
gdb.on('error',function (data) {
console.log('There was an error! (Error: '+data.msg+')');
});

gdb.on('saved',function (data) {
console.log('Content saved to database!');
});

console.log('Init called: '+gdb.get('Initcalled')); // will return false, as the DB isn't loaded.

function init (gdb) {
gdb.set('Initcalled',true);
console.log('Init called: '+gdb.get('Initcalled')); // SHOULD return true if you loaded the DB correctly.
this.save(); // Save when ever you feel like it. (probably best after adding content to the object.)
// Run your project...
};
30 changes: 30 additions & 0 deletions examples/example1.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
var GistDB = require('gistdb');

var gdb = new GistDB('USERNAME','PASSWORD');

var content = {example:'This is an example database!'};

gdb.create(content);

gdb.on('created',function (data) {
console.log('Database created!');
console.log(data);
this.load(this.gistid);
});

gdb.on('loaded',function (data) {
var date = new Date().getTime();
console.log('Current data: '+data);
console.log('Setting: test = '+date);
this.set('test',date);
console.log('Get "test": '+this.get('test'));
this.save();
});

gdb.on('saved',function (data) {
console.log('New data: '+data);
});

gdb.on('error',function (data) {
console.log(data);
});
35 changes: 35 additions & 0 deletions examples/example2.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
var GistDB = require('gistdb');

var gdb = new GistDB('USERNAME','PASSWORD');

var content = {example:'This is an example database!'};

gdb.create(content);

gdb.on('created',function (data) {
console.log('Database created!');
randomDataInsert(this);

});

gdb.on('saved',function (data) {
console.log('Saved!');
console.log('https://gist.github.com/'+data.id);
});

gdb.on('error',function (data) {
console.log(data);
});

function randomDataInsert (gdb) {
for (i = 0; i < 10; i++) {
gdb.set('Example'+i,Math.random()*10000);
}
console.log('Random data added.');
console.log('Content: '+JSON.stringify(gdb.content));
console.log('Saving data in 5 seconds.');
setTimeout(function(){
console.log('Saving.');
this.save();
}.bind(gdb),5000);
}
29 changes: 29 additions & 0 deletions examples/example3.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
var GistDB = require('gistdb');

gdb = new GistDB('USERNAME','PASSWORD');

content = {example:'This is an example database!'};

gdb.create(content,'example.db');

gdb.on('created',function (data) {
console.log('New database created! ('+data.id+')');
init(gdb);
});

gdb.on('saved',function (data) {
console.log('Content saved to database!');
});

gdb.on('error',function (data) {
console.log('There was an error! (Error: '+data.msg+')');
});

console.log('Init called: '+gdb.get('Initcalled')); // will return false, as the DB isn't loaded.

function init (gdb) {
gdb.set('Initcalled',true);
console.log('Init called: '+gdb.get('Initcalled')); // SHOULD return true if you loaded the DB correctly.
this.save(); // Save when ever you feel like it. (probably best after adding content to the object.)
// Run your project...
};
1 change: 1 addition & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
module.exports = require('./lib/GistDB.js');
136 changes: 136 additions & 0 deletions lib/GistDB.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
(function(){
var http_get = require('./http_get.js'),
util = require('util'),
events = require('events');

GistDB = function (user,pass,id) {
events.EventEmitter.call(this);
this.api_url = 'https://api.github.com';
this.user = user||null;
this.pass = pass||null;
this.gistid = id||null;
this.content = {};
this.opts = (this.user&&this.pass?{username:this.user,password:this.pass}:{});
this.opts.type = 'json';
};

util.inherits(GistDB,events.EventEmitter);

GistDB.prototype.getDBName = function (obj) {
var first;
for (var i in obj) {
if (obj.hasOwnProperty(i) && typeof(first) !== 'function') {
first = obj[i]; break;
}
}
return (first.filename?first.filename:false);
};

GistDB.prototype.load = function (id) {
if (!id && !this.gistid) {
this.emit('error',{msg:'You must supply an ID.',id:1});
return;
}
id = (id?id:this.gistid);
this.opts.method = 'GET';
http_get(this.api_url+'/gists/'+id,this.opts,function (data,err) {
if (!err) {
if (data.message) {
this.emit('error',{msg:data['message'],id:5});
return;
}
this.db = this.getDBName(data.files);
if (data.files[this.db]) {
if (data.files[this.db].content) {
this.gistid = data.id;
this.content = JSON.parse(data.files[this.db].content);
this.emit('loaded',{content:data.files[this.db].content,id:data.id});
} else {
this.emit('error',{msg:'No content in database.',id:3});
}
} else {
this.emit('error',{msg:'Could not find a database.',id:2});
}
} else {
this.emit('error',{msg:err,id:0});
}
}.bind(this));
};

GistDB.prototype.save = function () {
if (this.gistid) {
this.opts.method = 'PUT';
var data = this.content||{},
GIST = {description:'GistDB Database',files:{}};
GIST['files'][this.db] = {content:JSON.stringify(data)};
this.opts.postData = JSON.stringify(GIST);
http_get(this.api_url+'/gists/'+this.gistid,this.opts,function (data,err) {
if (!err) {
if (data.message) {
this.emit('error',{msg:data['message'],id:5});
return;
}
this.db = this.getDBName(data.files);
if (data.files[this.db]) {
if (data.files[this.db].content) {
this.gistid = data.id;
this.contect = JSON.parse(data.files[this.db].content);
this.emit('saved',{content:data.files[this.db].content,id:data.id});
} else {
this.emit('error',{msg:'No content in database.',id:5});
}
} else {
this.emit('error',{msg:'No such database.',id:2});
}
} else {
this.emit('error',{msg:err,id:0});
}
}.bind(this));
} else {
this.emit('error',{msg:'No gistid or database name set.',id:4});
}
};

GistDB.prototype.create = function (data,db,pub,desc) {
var data = data||{},
db = db||'undefined',
pub = pub||false,
desc = desc||'GistDB Database',
GIST = {description:desc,files:{}};
GIST['files'][db] = {content:JSON.stringify(data)};
this.opts.postData = JSON.stringify(GIST);
this.opts.method = "POST";
http_get(this.api_url+'/gists',this.opts,function (data,err) {
if (!err) {
if (data.message) {
this.emit('error',{msg:data['message'],id:5});
return;
}
this.db = (db?db:this.getDBName(data.files));
if (data.files[this.db]) {
if (data.files[this.db].content) {
this.gistid = data.id;
this.content = JSON.parse(data.files[this.db].content);
this.emit('created',{db:this['db'],id:data['id']});
} else {
this.emit('error',{msg:'No content in database.',id:3});
}
} else {
this.emit('error',{msg:'No such database.',id:2});
}
} else {
this.emit('error',{msg:err,id:0});
}
}.bind(this));
};

GistDB.prototype.set = function (name,data) {
this.content[name] = data;
}

GistDB.prototype.get = function (name) {
return this.content[name]||false;
}

module.exports = GistDB;
}).call(this);
98 changes: 98 additions & 0 deletions lib/http_get.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
(function(){
var crypto =
http_get = function (url, options, cb) {
var opts = {}, p;
if (!cb) {
cb = options;
options = {};
}
if (typeof(url) === 'string') {
opts = require('url').parse(url);
} else {
opts = url;
url = opts.herf;
}
for (var i in options) {
if (options.hasOwnProperty(i)) {
opts[i] = options[i];
}
}
opts.headers = opts.headers||{};
if ((p = get_proto()) === null) {
cb('unsupported protocol',1,null);
return;
}
if (opts.username && opts.password) {
opts.auth = opts.username+":"+opts.password;
}
opts.method = (opts.postData?"POST":"GET");
if (opts.method == 'POST' || opts.method == 'PUT') {
opts.headers["Content-Type"] = "application/x-www-form-urlencoded";
opts.headers["Content-Length"] = opts.postData.length;
}
var body = "";
var req = p.request(opts, function(res) {
res.setEncoding('utf8');
res.on('data', function(chunk) {
body += chunk;
}).on('end', function() {
if (opts.type) {
if (opts.type.toLowerCase() != 'auto') {
return cb(returnType(opts.type, body),null,res);
}
}
cb(body,null,res);
});
});
req.on('error', function(e) {
cb(e.message,null,null);
});
if (opts.postData) {
req.write(opts.postData);
}
req.end();
function returnType (type, body) {
switch (type.toLowerCase()) {
case 'jsdom':
var jsdom = require("jsdom")
var _jsdom = new jsdom.jsdom(body,null,{features:{QuerySelector: true}});
return _jsdom.createWindow();
case 'json':
return JSON.parse(body);
case 'xml':
var parser = require('xml2json');
return JSON.parse(parser.toJson(body));
default:
return body;
}
}
function get_proto() {
var s = opts.protocol.slice(0, -1).toLowerCase();
switch (s) {
case 'http':
case 'https':
return require(s);
default:
return null;
}
}
}
http_get.querystring = function(opts) {
return require('querystring').stringify(opts);
}
http_get.applyQuerystring = function(url, opts) {
var qs = require("querystring"),
ourl = require('url');
uo = ourl.parse(url)
us = qs.parse(uo.query||{});
for (var i in opts) {
if (opts.hasOwnProperty(i)) {
us[i] = opts[i]
}
}
uo.query = qs.stringify(us);
uo.search = "?"+uo.query
return ourl.format(uo);
}
module.exports = http_get;
}).call(this);
13 changes: 13 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{
"name": "gistdb",
"version": "0.0.1",
"author": {
"name": "Louis T.",
"email": "louist@ltdev.im",
"url": "http://github.com/LouisT/",
},
"keywords": ["gist","database","github"],
"description": "Use gist's from GitHub as database files.",
"engine": "node => 0.6.6",
"main": "gistdb",
}

0 comments on commit f0a7c16

Please sign in to comment.