Created
July 18, 2015 20:49
-
-
Save paranormal/4d962c5400833c244971 to your computer and use it in GitHub Desktop.
model.js
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
'use strict'; | |
var pg = require('pg'); | |
var config = require('../package.json'); | |
var client = new pg.Client(config.etc.pg); | |
function Model(input, output) { | |
if (!(this instanceof Model)) { | |
return new Model(input, output); | |
} | |
} | |
// table -> action structure | |
Model.prototype.SQL = { | |
LINKS: { | |
INSERT: 'INSERT INTO links (url) VALUES ($1)', | |
DELETE: 'DELETE FROM links WHERE url = $1', | |
SELECT: 'SELECT links.url FROM links' + | |
'LEFT JOIN posts ON links.id = posts.link_id' + | |
'WHERE url LIKE $1' | |
} | |
}; | |
// table accessor | |
Model.prototype.table = function(table) { | |
if (this.SQL[table]) { | |
this.table = table; | |
} else { | |
throw new Error('Wrong table name'); | |
} | |
return this; | |
}; | |
// action accessor | |
Model.prototype.action = function(action) { | |
if (!this.table) { | |
throw new Error('Set the table name first'); | |
} else { | |
if (this.SQL[this.table][action]) { | |
this.query = this.SQL[this.table][action]; | |
} else { | |
throw new Error('Wrong SQL action'); | |
} | |
} | |
return this; | |
}; | |
// data setter | |
Model.prototype.data = function(data) { | |
this.data = data; | |
return this; | |
}; | |
// input: a setup callback (return this), required | |
// output: a db query results callback, can be omited | |
// I know, I know, clever kills.... | |
Model.prototype.query = function(setup, output) { | |
setup(this); | |
client.connect(function(err) { | |
if(err) { | |
console.error(err); | |
process.exit(-1); | |
} | |
client.query(this.query, [this.data], function(err, results) { | |
if (err) { | |
console.error(err.message); | |
process.exit(-1); | |
} | |
if (output) { | |
output(results); | |
} | |
client.end(); | |
}); | |
}.bind(this)); | |
}; | |
module.exports = Model; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment