Permalink
Browse files

first commit

  • Loading branch information...
0 parents commit f0a7c164c1a1130865a41d7a46ab95a1bc60aa91 @LouisT committed Apr 28, 2012
Showing with 381 additions and 0 deletions.
  1. +39 −0 README.md
  2. +30 −0 examples/example1.js
  3. +35 −0 examples/example2.js
  4. +29 −0 examples/example3.js
  5. +1 −0 index.js
  6. +136 −0 lib/GistDB.js
  7. +98 −0 lib/http_get.js
  8. +13 −0 package.json
39 README.md
@@ -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 examples/example1.js
@@ -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 examples/example2.js
@@ -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 examples/example3.js
@@ -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 index.js
@@ -0,0 +1 @@
+module.exports = require('./lib/GistDB.js');
136 lib/GistDB.js
@@ -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 lib/http_get.js
@@ -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 package.json
@@ -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.