Skip to content

Commit

Permalink
working get and post communications with postgres db using node pg
Browse files Browse the repository at this point in the history
  • Loading branch information
shindigira committed Apr 1, 2016
1 parent 4eb9ab6 commit 869b44a
Show file tree
Hide file tree
Showing 7 changed files with 201 additions and 74 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
### node etc ###

node_modules
# Logs
logs
*.log
Expand Down Expand Up @@ -32,4 +33,4 @@ bower_components/
.floo
.floobit
.floo
.flooignore
.flooignore
1 change: 0 additions & 1 deletion EmbraceYourself
Submodule EmbraceYourself deleted from d80fd7
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
"jwt-simple": "^0.5.0",
"morgan": "^1.7.0",
"passport-http-token": "0.0.1",
"q": "^1.4.1"
"q": "^1.4.1",
"pg": "^4.5.2"
}
}
32 changes: 28 additions & 4 deletions server.js
Original file line number Diff line number Diff line change
@@ -1,22 +1,46 @@
var express = require('express');
var bodyParser = require('body-parser')
var bodyParser = require('body-parser');
// database dependencies
var pg = require('pg');
var connectionString = 'postgres://localhost:5432/test';

// database users
var userTableSure = require('./server/models/users/userModel.js').userTableSure;
var userController = require('./server/models/users/userController.js');
// database trips
var tripTableSure = require('./server/models/trips/tripModel.js').tripTableSure;

var app = express();
var port = process.env.PORT || 8000;

app.use( bodyParser.json() ); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true
}));
}));
app.use(express.static(__dirname + '/client'));
app.use('/scripts', express.static(__dirname + '/bower_components'));
//app.use('/scripts', express.static(__dirname + '/bower_components'));

app.get('/', function(req, res){
res.send("Rideshare server up and running!");
});

app.get('/data', function (req, res) {
console.log("Get Received!");
var client = new pg.Client(connectionString);
userController.getUsers(req, res, client);

});

app.post('/data', function (req, res) {
console.log("Post received!");
if (req.body) {
var client = new pg.Client(connectionString);
userController.newUser(req.body.firstname, req.body.lastname, req, res, client);
}
});

app.listen(port, function() {
console.log('App up and running on http://localhost: ', port);
});
userTableSure();
tripTableSure();
});
26 changes: 26 additions & 0 deletions server/models/trips/tripModel.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
// PostgresQL database Setup
// Official Documentation: https://github.com/brianc/node-postgres/wiki/pg
// Guide: http://mherman.org/blog/2015/02/12/postgresql-and-nodejs/

var pg = require('pg');
// var conString = "postgres://username:password@localhost/database";
var connectionString = process.env.DATABASE_URL || 'postgres://localhost:5432/test';

var tripTableSure = function () {

var client = new pg.Client(connectionString);

client.connect(function(err) {
if(err) {
return console.error('could not connect to postgres', err);
}
var query1 = client.query('CREATE TABLE IF NOT EXISTS trips(id SERIAL PRIMARY KEY, event VARCHAR(255))');

query1.on('end', function() { client.end(); });
});

}

module.exports = {
tripTableSure: tripTableSure
};
164 changes: 115 additions & 49 deletions server/models/users/userController.js
Original file line number Diff line number Diff line change
@@ -1,68 +1,134 @@
var User = require('./userModel.js'),
function tableSure (client) {

/*exmaple of how to make table relatonsips:
var User = sequelize.define('user', { name: Sequelize.STRING })
, Task = sequelize.define('task', { name: Sequelize.STRING })
, Tool = sequelize.define('tool', { name: Sequelize.STRING })
client.connect(function(err) {
if(err) {
return console.error('could not connect to postgres', err);
}
var query1 = client.query('CREATE TABLE IF NOT EXISTS users(id SERIAL PRIMARY KEY, firstname VARCHAR(255), lastname VARCHAR(255))');

Task.belongsTo(User)
User.hasMany(Task)
User.hasMany(Tool, { as: 'Instruments' })
var query2 = client.query('CREATE TABLE IF NOT EXISTS cars(id SERIAL PRIMARY KEY, text VARCHAR(255))');

// var query3 = client.query("INSERT INTO users (firstname, lastname) VALUES ('Bob', 'Barley')");

sequelize.sync().then(function() {
// this is where we continue ...
})
*/


module.exports = {


findAllUsers: function(req, res, next) {

User.findAll({ }).then(function(users) {
console.log(JSON.stringify(tasks));
query2.on('end', function() { client.end(); });
});
},


signup: function(req, res, next) {

User
.findOrCreate({where: {username: 'sdepold'}, defaults: {job: 'Technical Lead JavaScript'}})
.spread(function(user, created) {
console.log(user.get({
plain: true
}))
console.log(created)
}

/*EXAMPLE USER GOES HERE:
{
username: 'sdepold',
job: 'Technical Lead JavaScript',
id: 1,
createdAt: Fri Mar 22 2013 21: 28: 34 GMT + 0100(CET),
updatedAt: Fri Mar 22 2013 21: 28: 34 GMT + 0100(CET)
}
created: true
*/
});
},
function getUsers (req, res, client) {
var results = [];
client.connect(function(err) {
if(err) {
console.error('get failed!');
return res.status(500).json({ success: false, data: err});
}

var query = client.query('SELECT * FROM users');

signin: function(req, res, next) {
query.on('row', function(row) {
results.push(row);
});

//code goes here
query.on('end', function() {
client.end();
return res.json(results);
});
}); // end client.connect
}

},
function newUser (firstname, lastname, req, res, client) {

client.connect(function(err) {
if(err) {
console.error('post failed!');
return res.status(500).json({ success: false, data: err});
}

checkAuth: function(req, res, next) {
var query = client.query("INSERT INTO users(firstname, lastname) values($1, $2)", [firstname, lastname]);

//code goes here

}
query.on('end', function() {
client.end();
return res.status(302);
});

}); // end client.connect
}

};
module.exports = {
tableSure: tableSure,
getUsers: getUsers,
newUser: newUser
};


// var User = require('./userModel.js'),
//
// /*exmaple of how to make table relatonsips:
// var User = sequelize.define('user', { name: Sequelize.STRING })
// , Task = sequelize.define('task', { name: Sequelize.STRING })
// , Tool = sequelize.define('tool', { name: Sequelize.STRING })
//
// Task.belongsTo(User)
// User.hasMany(Task)
// User.hasMany(Tool, { as: 'Instruments' })
//
//
// sequelize.sync().then(function() {
// // this is where we continue ...
// })
// */
//
//
// module.exports = {
//
//
// findAllUsers: function(req, res, next) {
//
// User.findAll({ }).then(function(users) {
// console.log(JSON.stringify(tasks));
// });
// },
//
//
// signup: function(req, res, next) {
//
// User
// .findOrCreate({where: {username: 'sdepold'}, defaults: {job: 'Technical Lead JavaScript'}})
// .spread(function(user, created) {
// console.log(user.get({
// plain: true
// }))
// console.log(created)
//
// /*EXAMPLE USER GOES HERE:
// {
// username: 'sdepold',
// job: 'Technical Lead JavaScript',
// id: 1,
// createdAt: Fri Mar 22 2013 21: 28: 34 GMT + 0100(CET),
// updatedAt: Fri Mar 22 2013 21: 28: 34 GMT + 0100(CET)
// }
// created: true
// */
// });
// },
//
//
// signin: function(req, res, next) {
//
// //code goes here
//
// },
//
//
// checkAuth: function(req, res, next) {
//
// //code goes here
//
// }
//
//
// };
46 changes: 28 additions & 18 deletions server/models/users/userModel.js
Original file line number Diff line number Diff line change
@@ -1,19 +1,29 @@
var User = sequelize.define('user', {
firstName: {
type: Sequelize.STRING,
field: 'first_name' // Will result in an attribute that is firstName when user facing but first_name in the database
},
lastName: {
type: Sequelize.STRING
}
}, {
freezeTableName: true // Model tableName will be the same as the model name
});

User.sync({force: true}).then(function () {
// Table created
return User.create({
firstName: 'John',
lastName: 'Hancock'
// PostgresQL database Setup
// Official Documentation: https://github.com/brianc/node-postgres/wiki/pg
// Guide: http://mherman.org/blog/2015/02/12/postgresql-and-nodejs/

var pg = require('pg');
// var conString = "postgres://username:password@localhost/database";
var connectionString = process.env.DATABASE_URL || 'postgres://localhost:5432/test';

var userTableSure = function () {

var client = new pg.Client(connectionString);

client.connect(function(err) {
if(err) {
return console.error('could not connect to postgres', err);
}
var query1 = client.query('CREATE TABLE IF NOT EXISTS users(id SERIAL PRIMARY KEY, firstname VARCHAR(255), lastname VARCHAR(255))');

query1.on('end', function() { client.end(); });
});
});

}

module.exports = {
userTableSure: userTableSure
};

// var query2 = client.query('CREATE TABLE IF NOT EXISTS cars(id SERIAL PRIMARY KEY, text VARCHAR(255))');
// query2.on('end', function() { client.end(); });

0 comments on commit 869b44a

Please sign in to comment.