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

Aaron Saloff assignment #19

Open
wants to merge 6 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
Binary file added .DS_Store
Binary file not shown.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
node_modules/
1 change: 1 addition & 0 deletions Procfile
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
web: node app.js
113 changes: 113 additions & 0 deletions app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
const express = require('express');
const app = express();


// Body Parser
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));


// Method Override
app.use((req, res, next) => {
if (req.query._method || (typeof req.body === 'object' && req.body._method)) {
let method = req.query._method || req.body._method;
req.method = method.toUpperCase();
req.url = req.path;
}
next();
});


// Public
app.use(express.static(`${__dirname}/public`));


// Logging
const logger = require('morgan');
const morganToolkit = require('morgan-toolkit')(logger);

app.use(morganToolkit());


// Sessions/Cookies
var cookieSession = require('cookie-session');
const cookieParser = require('cookie-parser');

app.use(cookieParser());
app.use(cookieSession({
name: 'session',
keys: ['asdf1234567890qwer']
}));


// Flash Messages
var flash = require('express-flash-messages');
app.use(flash());


// Database
const mongoose = require('mongoose');
app.use((req, res, next) => {
if (mongoose.connection.readyState) {
next();
} else {
require('./mongo')().then(() => next());
}
});


// Authentication Redirection
const authRedirect = require('./lib/auth_redirect');
app.use(authRedirect);


// Routes
const index = require('./routers/index');
const users = require('./routers/users');
const posts = require('./routers/posts');
const comments = require('./routers/comments');

app.use('/', index);
app.use('/users', users);
app.use('/posts', posts);
app.use('/comments', comments);


// Template Engine
const expressHandlebars = require('express-handlebars');
const helpers = require('./helpers');

const hbs = expressHandlebars.create({
helpers: helpers,
partialsDir: 'views/',
defaultLayout: 'application',
extname: '.hbs'
});

app.engine('hbs', hbs.engine);
app.set('view engine', 'hbs');


// Server
var port = process.env.PORT ||
process.argv[2] ||
3000;
var host = 'localhost';

var args;
if (process.env.NODE_ENV === 'production') {
args = [port];
} else {
args = [port, host];
}

args.push(() => {
console.log(`Listening: http://${ host }:${ port }`);
});

const server = app.listen.apply(app, args);

// Web Socket
const io = require('socket.io').listen(server);
const socket = require('./lib/socket_service');
socket.setup(io);
13 changes: 13 additions & 0 deletions config/mongo.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{
"development": {
"database": "thoreddit_development",
"host": "localhost"
},
"test": {
"database": "thoreddit_test",
"host": "localhost"
},
"production": {
"use_env_variable": "MONGODB_URI"
}
}
11 changes: 11 additions & 0 deletions helpers/flashHelper.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
const FlashHelper = {};

FlashHelper.bootstrapAlertClassFor = function(key) {
return {
"error": "danger",
"alert": "danger",
"notice": "info"
}[key] || key;
};

module.exports = FlashHelper;
6 changes: 6 additions & 0 deletions helpers/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
const HelperLoader = require('load-helpers');
const helperLoader = new HelperLoader();

const helpers = helperLoader.load('helpers/*Helper.js').cache;

module.exports = helpers;
17 changes: 17 additions & 0 deletions helpers/postsHelper.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
var PostsHelper = {};

PostsHelper.postsPath = () => '/posts';
PostsHelper.postPath = (id) => `/posts/${ id }`;
PostsHelper.newPostPath = () => '/posts/new';
PostsHelper.editPostPath = (id) => `/posts/${ id }/edit`;
PostsHelper.destroyPostPath = (id) => `/posts/${ id }?_method=delete`;

PostsHelper.postFormAction = (post) => {
if (post) {
return `/posts/${ post.id }`;
} else {
return '/posts';
}
};

module.exports = PostsHelper;
17 changes: 17 additions & 0 deletions helpers/usersHelper.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
var UsersHelper = {};

UsersHelper.usersPath = () => '/users';
UsersHelper.userPath = (id) => `/users/${ id }`;
UsersHelper.newUserPath = () => '/users/new';
UsersHelper.editUserPath = (id) => `/users/${ id }/edit`;
UsersHelper.destroyUserPath = (id) => `/users/${ id }?_method=delete`;

UsersHelper.userFormAction = (user) => {
if (user) {
return `/users/${ user.id }`;
} else {
return '/users';
}
};

module.exports = UsersHelper;
12 changes: 12 additions & 0 deletions helpers/viewHelper.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
var ViewHelper = {};

ViewHelper.formatDate = (date) => {
date = new Date(date);
return `${date.getMonth() + 1}/${date.getDate()}/${date.getFullYear()}`;
};

ViewHelper.voteScore = doc => {
return doc.totalScore();
};

module.exports = ViewHelper;
31 changes: 31 additions & 0 deletions lib/auth_redirect.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
const User = require('../models').User;

const AuthRedirection = (req, res, next) => {
var userId = req.cookies.currentUser;

if (req.url !== '/login') {
User.findById(userId)
.then(user => {
if (!user) throw 'No Current User';
next();
})
.catch(e => {
res.redirect('/login');
});
} else {
User.findById(userId)
.then(user => {
if (user) throw 'Already Logged in';
next();
})
.catch(e => {
if (e === 'Already Logged in') {
res.redirect('/');
} else {
res.redirect('/login');
}
});
}
};

module.exports = AuthRedirection;
81 changes: 81 additions & 0 deletions lib/socket_service.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
const models = require('../models');
const Post = models.Post;
const Comment = models.Comment;
const Vote = models.Vote;

var Socket = {};

Socket.setup = (io) => {
io.on('connection', client => {
console.log('Socket connected');

client.on('registerVote', voteData => {
const Model = voteData.model === 'post' ? Post : Comment;

Model.findById(voteData.docId)
.populate('votes')
.then(doc => {
// Check if the user has already voted
var votes = doc.votes;
var currentUserVote, newVote;

for (let vote of votes) {
if (vote.user == voteData.currentUserId) {
currentUserVote = vote;
}
}

var totalScore = doc.totalScore();

if (!currentUserVote) {
// if there is no vote, create a vote
createNewVote(doc, voteData.currentUserId, voteData.voteType);
voteData.voteType === 'upvote' ? totalScore += 1 : totalScore -= 1;
} else {

// if user clicked upvote
if (voteData.voteType === 'upvote') {
if (currentUserVote.upvote === true) {
deleteVote(currentUserVote, doc);
totalScore -= 1;
} else {
currentUserVote.upvote = true;
currentUserVote.save();
totalScore += 2;
}
} else {

// if user clicked downvote
if (currentUserVote.upvote === true) {
currentUserVote.upvote = false;
currentUserVote.save();
totalScore -= 2;
} else {
deleteVote(currentUserVote, doc);
totalScore += 1;
}
}
}

const scoreInfo = { score: totalScore, model: voteData.model, docId: doc.id };

io.emit('score-update', scoreInfo);
});
});
});
};

const createNewVote = (post, userId, voteType) => {
var type = voteType === 'upvote' ? true : false;
newVote = new Vote({ user: userId, upvote: type });
post.votes.push(newVote);
newVote.save();
post.save();
};

const deleteVote = (vote, parentDoc) => {
parentDoc.removeVote(vote);
vote.remove();
};

module.exports = Socket;
27 changes: 27 additions & 0 deletions models/comment.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const Interactable = require('./interactable');

const CommentSchema = new Schema({
body: {
type: String,
required: true
},
user: {
type: Schema.Types.ObjectId,
ref: 'User',
required: true
},
originalPost: {
type: Schema.Types.ObjectId,
ref: 'Post',
required: true
}
}, {
timestamps: true,
discriminatorKey: 'kind'
});

const Comment = Interactable.discriminator('Comment', CommentSchema);

module.exports = Comment;
13 changes: 13 additions & 0 deletions models/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
const mongoose = require('mongoose');
const bluebird = require('bluebird');

mongoose.Promise = bluebird;

const models = {};

models.User = require('./user');
models.Post = require('./post');
models.Comment = require('./comment');
models.Vote = require('./vote');

module.exports = models;
36 changes: 36 additions & 0 deletions models/interactable.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const InteractableSchema = new Schema({
comments: [{
type: Schema.Types.ObjectId,
ref: 'Comment'
}],
votes: [{
type: Schema.Types.ObjectId,
ref: 'Vote'
}]
}, {
timestamps: true,
discriminatorKey: 'kind'
});

InteractableSchema.methods.totalScore = function() {
var score = 0;

for (let vote of this.votes) {
if (!vote.id) throw 'Votes have not been populated';
vote.upvote ? score += 1 : score -= 1;
}
return score;
};

InteractableSchema.methods.removeVote = function(vote) {
var index = this.votes.indexOf(vote.id);
this.votes.splice(index, 1);
this.save();
};

const Interactable = mongoose.model('Interactable', InteractableSchema);

module.exports = Interactable;
Loading