Skip to content

Instantly share code, notes, and snippets.

@pagameba
Created January 24, 2011 19:54
Show Gist options
  • Save pagameba/793834 to your computer and use it in GitHub Desktop.
Save pagameba/793834 to your computer and use it in GitHub Desktop.
config.json:
{
"database": {
"connection": "pg://postgres:[email protected]:5432/test"
},
"web": {
"port": 8000
}
}
server.js:
var fs = require('fs'),
path = require('path'),
express = require('express'), // included with boilerplate
Seq = require('seq'), // npm install seq
pg = require('pg'), // npm install pg
configFile = path.join(__dirname, 'config.json'),
config = null;
Seq()
.seq( function() { fs.readFile(configFile, this); } )
.seq( function(data) {
config = JSON.parse(data.toString());
pg.connect(config.database.connection, this);
)
.seq( function(client) {
config.database.client = client;
fs.readdir(path.join(__dirname, 'sql'), this);
})
/* what do I do here ? */
.flatten()
.parEach(function(file) {
if (path.extname(file) == '.sql') {
var table = path.basename(file, '.sql');
console.log('checking for existance of ' + table);
var sql = "SELECT relname FROM pg_class WHERE relname = '"+file+"';";
config.database.client.query(sql, function(err, result) {
if (err) {
//send err to seq
} else if (result.rows.length == 0) {
fs.readFile(path.join(__dirname, 'sql', file), function(err, data) {
if (!err) {
config.database.client.query(data.toString(), function(err, result) {
if (err) {
//send to seq
} else {
// this table is okay
}
});
} else {
// send err to seq?
}
})
} else {
// this table is okay
}
});
}
})
/* don't want to get to this point until all tables have been created */
.seq( startServer )
.catch(function(err) { // report startup errors
console.error(err.stack ? err.stack : err);
});
function startServer() {
server = express.createServer();
server.configure( /* ... */ );
server.listen(config.web.port || 8000);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment