Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Tweedrs #25

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 52 additions & 0 deletions controllers/tweets.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
module.exports = (db) => {

/**
* ===========================================
* Controller logic
* ===========================================
*/

const index = (req, res) => {
db.tweets.getAll(req.cookies['loggedIn'], req.cookies['name'], (err, result) => {
res.render('home', result);
});
};

const sign = (req, res) => {
db.tweets.sign( req.body, (err, result, func, nameCookie) => {
switch (func) {
case 'signout':
res.clearCookie('loggedIn');
res.clearCookie('name');
res.redirect('/');
break;

case 'signin':
res.cookie('loggedIn', true);
res.cookie('name', nameCookie);
res.redirect('/');
break;

default:
res.redirect('/');
}
});
};

const create = (req, res) => {
db.tweets.create( req.body, req.cookies['name'], (err, result) => {
res.redirect('/');
});
};

/**
* ===========================================
* Export controller functions as a module
* ===========================================
*/
return {
index,
sign,
create,
};
}
24 changes: 24 additions & 0 deletions db.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
const pg = require('pg');
const tweets = require('./models/tweets');

const configs = {
user: 'postgres',
host: '127.0.0.1',
database: 'tweedr',
port: 5432,
password: 'pg'
};
const pool = new pg.Pool(configs);
pool.on('error', function (err) {
console.log('idle client error', err.message, err.stack);
});

module.exports = {
queryInterface: (text, params, callback) => {
return pool.query(text, params, callback);
},

tweets: tweets(pool),

pool: pool
};
171 changes: 120 additions & 51 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,91 +1,160 @@
const express = require('express');
const methodOverride = require('method-override');
const cookieParser = require('cookie-parser');

const pg = require('pg');

const sha256 = require('js-sha256');
const db = require('./db');
/**
* ===================================
* Configurations and set up
* ===================================
*/

const configs = {
user: 'akira',
host: '127.0.0.1',
database: 'testdb',
port: 5432,
};

const pool = new pg.Pool(configs);

pool.on('error', function (err) {
console.log('idle client error', err.message, err.stack);
});

// Init express app
const app = express();

// Set up middleware
app.use(methodOverride('_method'));
app.use(cookieParser());
app.use(express.urlencoded({
extended: true
}));

// Set react-views to be the default view engine
const reactEngine = require('express-react-views').createEngine();
app.set('views', __dirname + '/views');
app.set('view engine', 'jsx');
app.engine('jsx', reactEngine);

/**
* ===================================
* Routes
* ===================================
*/

// Root GET request (it doesn't belong in any controller file)
app.get('/', (request, response) => {
response.send('Welcome To Tweedr.');
});

app.get('/users/new', (request, response) => {
response.render('user/newuser');
});

app.post('/users', (request, response) => {

const queryString = 'INSERT INTO users (name, password) VALUES ($1, $2)';
const values = [
request.body.name,
request.body.password
];

// execute query
pool.query(queryString, values, (error, queryResult) => {
//response.redirect('/');
response.send('user created');
});
});



require('./routes')(app, db);
//==============================================================



// SHOW ALL TWEETS
//==============================================================
// app.get('/', (req, res) => {
// let query = "SELECT * FROM tweets INNER JOIN users ON (tweets.author_id = users.id) ORDER BY tweeted_on DESC;";

// pool.query(query, (err, result) => {
// if (err) {
// console.error('query error:', err.stack);
// res.send( 'query error' );
// } else {
// let resultArr = [result.rows];
// resultArr.push(req.cookies['loggedIn']);

// if (req.cookies['loggedIn']) {
// query = `SELECT * FROM users WHERE name='${req.cookies['name']}';`;
// pool.query(query, (err, result) => {
// if (err) {
// console.error('query error:', err.stack);
// res.send( 'query error' );
// } else {
// resultArr.push(result.rows);
// res.render('home', resultArr);
// }
// })
// } else {
// res.render('home', resultArr);
// }
// }
// });
// });

// //SIGN UP SIGN IN SIGN OUT
// //==============================================================
// app.post('/users/new', (req, res) => {
// switch (req.body.func) {
// case 'signin':
// let query = `SELECT * FROM users WHERE name='${req.body.name}'`;
// pool.query(query, (err, result) => {
// if (err) {
// console.error('query error:', err.stack);
// res.send( 'query error' );
// } else {
// if ( result.rows.length === 0 ) {
// res.redirect('/');
// } else {
// const user = result.rows[0];
// let password = user.password;
// if (password == sha256(req.body.password)) {
// res.cookie('loggedIn', true);
// res.cookie('name', req.body.name);
// res.redirect('/');
// } else {
// res.redirect('/');
// }
// }
// }
// });
// break;

// case 'signout':
// res.clearCookie('loggedIn');
// res.clearCookie('name');
// res.redirect('/');
// break;

// case 'signup':
// const values = [req.body.name, sha256(req.body.password)];
// let text = "INSERT INTO users (name, password) VALUES ($1, $2)";

// pool.query(text, values, (err, result) => {
// if (err) {
// console.error('query error:', err.stack);
// res.send( 'query error' );
// } else {
// res.cookie('loggedIn', true);
// res.cookie('name', req.body.name);
// res.redirect('/');
// }
// });
// break;
// }
// });

// //CREATE TWEET
// //==============================================================
// app.post('/', (req, res) => {
// let query = `SELECT * FROM users WHERE name='${req.cookies['name']}';`;

// pool.query(query, (err, result) => {
// if (err) {
// console.error('query error:', err.stack);
// res.send( 'query error' );
// } else {
// let query =`INSERT INTO tweets (content, author_id) VALUES ('${req.body.tweet}', ${result.rows[0].id})`;

// pool.query(query, (err, result) => {
// if (err) {
// console.error('query error:', err.stack);
// res.send( 'query error' );
// } else {
// res.redirect('/');
// }
// });
// }
// });
// });





//==============================================================
/**
* ===================================
* Listen to requests on port 3000
* ===================================
*/

const server = app.listen(3000, () => console.log('~~~ Tuning in to the waves of port 3000 ~~~'));

let onClose = function(){

server.close(() => {
console.log('Process terminated')
pool.end( () => console.log('Shut down db connection pool'));
})
};

process.on('SIGTERM', onClose);
process.on('SIGINT', onClose);
process.on('SIGINT', onClose);
105 changes: 105 additions & 0 deletions models/tweets.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
const cookieParser = require('cookie-parser');
const sha256 = require('js-sha256');
module.exports = (dbPoolInstance) => {

// `dbPoolInstance` is accessible within this function scope
let getAll = (loggedinCookie, nameCookie, callback) => {
let query = "SELECT * FROM tweets INNER JOIN users ON (tweets.author_id = users.id) ORDER BY tweeted_on DESC;";
dbPoolInstance.query(query, (err, result) => {
if (err) {
console.error('query error:', err.stack);
callback(err, null);
} else {
let resultArr = [result.rows];
resultArr.push(loggedinCookie);

if (loggedinCookie) {
query = `SELECT * FROM users WHERE name='${nameCookie}';`;
dbPoolInstance.query(query, (err, result) => {
if (err) {
console.error('query error:', err.stack);
callback(err, null);
} else {
resultArr.push(result.rows);
callback(err, resultArr);
}
})
} else {
callback(err, resultArr);
}
}
});
};

let sign = (userForm, callback) => {
switch (userForm.func) {
case 'signin':
let query = `SELECT * FROM users WHERE name='${userForm.name}'`;
dbPoolInstance.query(query, (err, result) => {
if (err) {
console.error('query error:', err.stack);
callback(err, null);
} else {
if ( result.rows.length === 0 ) {
callback(null, null);
} else {
const user = result.rows[0];
let password = user.password;
if (password == sha256(userForm.password)) {
callback(null, null, 'signin', userForm.name);
} else {
callback(null, null);
}
}
}
});
break;

case 'signout':
callback(null, null, 'signout');
break;

case 'signup':
const values = [userForm.name, sha256(userForm.password)];
let text = "INSERT INTO users (name, password) VALUES ($1, $2)";

dbPoolInstance.query(text, values, (err, result) => {
if (err) {
console.error('query error:', err.stack);
callback(err, null);
} else {
callback(null, null, 'signin', userForm.name);
}
});
break;
}
};

let create = (userForm, nameCookie, callback) => {
let query = `SELECT * FROM users WHERE name='${nameCookie}';`;

dbPoolInstance.query(query, (err, result) => {
if (err) {
console.error('query error:', err.stack);
callback(err, null);
} else {
let query =`INSERT INTO tweets (content, author_id) VALUES ('${userForm.tweet}', ${result.rows[0].id})`;

dbPoolInstance.query(query, (err, result) => {
if (err) {
console.error('query error:', err.stack);
callback(err, null);
} else {
callback(null, null);
}
});
}
});
};

return {
getAll,
sign,
create,
};
};
Loading