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

Part2: Refactoring 1 route to MVC done, cause sometimes, you gotta do things the hard way. #38

Open
wants to merge 2 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
28 changes: 28 additions & 0 deletions controllers/tweedrC.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
module.exports = (db) => {

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

let index = (request, response) => {
db.tweedr.getAllTweets((error, allTweets) => {
response.render('testpage', {
allTweets
});
});
};


/**
* ===========================================
* Export controller functions as a module
* ===========================================
*/

return {
index,
};

}
52 changes: 52 additions & 0 deletions db.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
const pg = require('pg');
const tweedr = require('./models/tweedrM');
const url = require('url');


var configs;

if (process.env.DATABASE_URL) {

const params = url.parse(process.env.DATABASE_URL);
const auth = params.auth.split(':');

configs = {
user: auth[0],
password: auth[1],
host: params.hostname,
port: params.port,
database: params.pathname.split('/')[1],
ssl: true
};

} else {
configs = {
user: 'cash',
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);
});

module.exports = {
/*
* ADD APP MODELS HERE
*/
tweedr: tweedr(pool),


//make queries directly from here
queryInterface: (text, params, callback) => {
return pool.query(text, params, callback);
},

// get a reference to end the connection pool at server end
pool: pool
};
117 changes: 92 additions & 25 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,16 +11,16 @@ const pg = require('pg');
*/

const configs = {
user: 'akira',
host: '127.0.0.1',
database: 'testdb',
port: 5432,
user: 'cash',
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);
console.log('idle client error', err.message, err.stack);
});

// Init express app
Expand All @@ -30,7 +30,7 @@ const app = express();
app.use(methodOverride('_method'));
app.use(cookieParser());
app.use(express.urlencoded({
extended: true
extended: true
}));

// Set react-views to be the default view engine
Expand All @@ -45,47 +45,114 @@ app.engine('jsx', reactEngine);
* ===================================
*/

// Root GET request (it doesn't belong in any controller file)
app.get('/', (request, response) => {
response.send('Welcome To Tweedr.');
// Root GET req (it doesn't belong in any controller file)
app.get('/', (req, res) => {
let loggedin = req.cookies['loggedin'];
if (loggedin == undefined) {
res.render('main')
} else {
let tempArr = [];
let getusers = `select * from users;`
let gettweets = `select * from tweets;`
let getfollows = `select * from getfollows;`
pool.query(getusers, (err, result1) => {
tempArr.push(result1.rows);
})
pool.query(gettweets, (err, result2) => {
tempArr.push(result2.rows);
})
pool.query(getfollows, (err, result3) => {
tempArr.push(result3.rows);
})
let passObj = {
tempArr
}
res.render('loggedmain', {
passObj: passObj
});
};
});

app.get('/users/new', (request, response) => {
response.render('user/newuser');
app.post('/login', (req, res) => {
let testlogin = `select * from users where username='${req.body.username}';`
pool.query(testlogin, (err, result) => {
if (result.rows.length == 0) {
console.log(req.body.username)
console.log('username error')
res.render('loginerror');
} else {
if (result.rows[0].password == req.body.password) {
let tempArr = [];
tempArr.push(result.rows)
let getusers = `select * from users;`
let gettweets = `select * from tweets;`
let getfollows = `select * from getfollows;`
pool.query(getusers, (err1, result1) => {
tempArr.push(result1.rows);
pool.query(gettweets, (err2, result2) => {
tempArr.push(result2.rows);
pool.query(getfollows, (err3, result3) => {
tempArr.push(result3.rows);
})
})
})
let passObj = {
tempArr
}
res.render('loggedmain', {
passObj: passObj
});
} else {
console.log('password error')
res.render('loginerror');
};
};
});
});

app.get('/users/new', (req, res) => {
res.render('createacc');
});

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

const queryString = 'INSERT INTO users (name, password) VALUES ($1, $2)';
app.post('/users', (req, res) => {

const queryString = 'INSERT INTO users (username, firstname, lastname, password, email) VALUES ($1, $2, $3, $4, $5)';
const values = [
request.body.name,
request.body.password
req.body.username,
req.body.firstname,
req.body.lastname,
req.body.password,
req.body.email
];

// execute query
pool.query(queryString, values, (error, queryResult) => {
//response.redirect('/');
response.send('user created');
//res.redirect('/');
if (error) {
console.log(error.stack)
}
console.log('user created');
res.render('main');
});
});



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

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

let onClose = function(){
let onClose = function () {

server.close(() => {
console.log('Process terminated')
pool.end( () => console.log('Shut down db connection pool'));
})
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);
39 changes: 39 additions & 0 deletions models/tweedrM.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
/**
* ===========================================
* Export model functions as a module
* ===========================================
*/
module.exports = (dbPoolInstance) => {

// `dbPoolInstance` is accessible within this function scope

let getAllTweets = (callback) => {
// const values = [type_id];
let query = 'SELECT * FROM tweets;';

dbPoolInstance.query(query, (error, queryResult) => {
if (error) {

// invoke callback function with results after query has executed
callback(error, null);

} else {

// invoke callback function with results after query has executed

if (queryResult.rows.length > 0) {
callback(null, queryResult.rows);

} else {
callback(null, null);

}
}
});
};

return {
getAllTweets,
//get,
};
};
65 changes: 65 additions & 0 deletions newindex.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
const express = require('express');
const methodOverride = require('method-override');
const cookieParser = require('cookie-parser');
const db = require('./db');

/**
* ===================================
* Configurations and set up
* ===================================
*/

// 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
* ===================================
*/

// Import routes to match incoming requests
require('./routes')(app, db);

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

// Catch all unmatched requests and return 404 not found page
app.get('*', (request, response) => {
response.render('notfound');
});

/**
* ===================================
* Listen to requests on port 3000
* ===================================
*/
const PORT = process.env.PORT || 3000;

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

let onClose = function () {

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

process.on('SIGTERM', onClose);
process.on('SIGINT', onClose);
Empty file added removetables.sql
Empty file.
12 changes: 12 additions & 0 deletions routes.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
module.exports = (app, db) => {

const tweedr = require('./controllers/tweedrC')(db);

/*
* =========================================
* Routes for one controller
* =========================================
*/

app.get('/', tweedr.index);
};
Loading