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

Made code leaner by outsourcing routes logic to controllers and updated the entire project to use ES6+ syntax #104

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
12 changes: 6 additions & 6 deletions app.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
var http = require('http'),
const http = require('http'),
path = require('path'),
methods = require('methods'),
express = require('express'),
Expand All @@ -9,10 +9,10 @@ var http = require('http'),
errorhandler = require('errorhandler'),
mongoose = require('mongoose');

var isProduction = process.env.NODE_ENV === 'production';
const isProduction = process.env.NODE_ENV === 'production';

// Create global app object
var app = express();
const app = express();

app.use(cors());

Expand Down Expand Up @@ -45,7 +45,7 @@ require('./config/passport');
app.use(require('./routes'));

/// catch 404 and forward to error handler
app.use(function(req, res, next) {
app.use((req, res, next) => {
var err = new Error('Not Found');
err.status = 404;
next(err);
Expand All @@ -56,7 +56,7 @@ app.use(function(req, res, next) {
// development error handler
// will print stacktrace
if (!isProduction) {
app.use(function(err, req, res, next) {
app.use((err, req, res, next) => {
console.log(err.stack);

res.status(err.status || 500);
Expand All @@ -70,7 +70,7 @@ if (!isProduction) {

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
app.use((err, req, res, next) => {
res.status(err.status || 500);
res.json({'errors': {
message: err.message,
Expand Down
11 changes: 5 additions & 6 deletions config/passport.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var mongoose = require('mongoose');
var User = mongoose.model('User');
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const mongoose = require('mongoose');
const User = mongoose.model('User');

passport.use(new LocalStrategy({
usernameField: 'user[email]',
passwordField: 'user[password]'
}, function(email, password, done) {
}, (email, password, done) => {
User.findOne({email: email}).then(function(user){
if(!user || !user.validPassword(password)){
return done(null, false, {errors: {'email or password': 'is invalid'}});
Expand All @@ -15,4 +15,3 @@ passport.use(new LocalStrategy({
return done(null, user);
}).catch(done);
}));

254 changes: 254 additions & 0 deletions controllers/articles.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,254 @@
const mongoose = require('mongoose');
const Article = mongoose.model('Article');
const Comment = mongoose.model('Comment');
const User = mongoose.model('User');

exports.getArticlesController = (req, res, next) => {
let query = {};
let limit = 20;
let offset = 0;

if(typeof req.query.limit !== 'undefined'){
limit = req.query.limit;
}

if(typeof req.query.offset !== 'undefined'){
offset = req.query.offset;
}

if( typeof req.query.tag !== 'undefined' ){
query.tagList = {"$in" : [req.query.tag]};
}

Promise.all([
req.query.author ? User.findOne({username: req.query.author}) : null,
req.query.favorited ? User.findOne({username: req.query.favorited}) : null
]).then(results => {
let author = results[0];
let favoriter = results[1];

if(author){
query.author = author._id;
}

if(favoriter){
query._id = {$in: favoriter.favorites};
} else if(req.query.favorited){
query._id = {$in: []};
}

return Promise.all([
Article.find(query)
.limit(Number(limit))
.skip(Number(offset))
.sort({createdAt: 'desc'})
.populate('author')
.exec(),
Article.count(query).exec(),
req.payload ? User.findById(req.payload.id) : null,
]).then(results => {
let articles = results[0];
let articlesCount = results[1];
let user = results[2];

return res.json({
articles: articles.map(article => {
return article.toJSONFor(user);
}),
articlesCount: articlesCount
});
});
}).catch(next);
};


exports.getArticleFeedController = (req, res, next) => {
let limit = 20;
let offset = 0;

if(typeof req.query.limit !== 'undefined'){
limit = req.query.limit;
}

if(typeof req.query.offset !== 'undefined'){
offset = req.query.offset;
}

User.findById(req.payload.id).then(user => {
if (!user) { return res.sendStatus(401); }

Promise.all([
Article.find({ author: {$in: user.following}})
.limit(Number(limit))
.skip(Number(offset))
.populate('author')
.exec(),
Article.count({ author: {$in: user.following}})
]).then(results => {
let articles = results[0];
let articlesCount = results[1];

return res.json({
articles: articles.map(article =>{
return article.toJSONFor(user);
}),
articlesCount: articlesCount
});
}).catch(next);
});
};


exports.postArticlesController = (req, res, next) => {
User.findById(req.payload.id).then(user => {
if (!user) { return res.sendStatus(401); }

const article = new Article(req.body.article);

article.author = user;

return article.save().then(() => {
console.log(article.author);
return res.json({article: article.toJSONFor(user)});
});
}).catch(next);
};


exports.getArticleReturnController = (req, res, next) => {
Promise.all([
req.payload ? User.findById(req.payload.id) : null,
req.article.populate('author').execPopulate()
]).then(results => {
let user = results[0];

return res.json({article: req.article.toJSONFor(user)});
}).catch(next);
};


exports.updateArticleController = (req, res, next) => {
User.findById(req.payload.id).then(user => {
if(req.article.author._id.toString() === req.payload.id.toString()){
if(typeof req.body.article.title !== 'undefined'){
req.article.title = req.body.article.title;
}

if(typeof req.body.article.description !== 'undefined'){
req.article.description = req.body.article.description;
}

if(typeof req.body.article.body !== 'undefined'){
req.article.body = req.body.article.body;
}

if(typeof req.body.article.tagList !== 'undefined'){
req.article.tagList = req.body.article.tagList
}

req.article.save().then(article => {
return res.json({article: article.toJSONFor(user)});
}).catch(next);
} else {
return res.sendStatus(403);
}
});
};


exports.deleteArticleController = (req, res, next) => {
User.findById(req.payload.id).then(user =>{
if (!user) { return res.sendStatus(401); }

if(req.article.author._id.toString() === req.payload.id.toString()){
return req.article.remove().then(() => {
return res.sendStatus(204);
});
} else {
return res.sendStatus(403);
}
}).catch(next);
};


exports.favoriteArticleController = (req, res, next) => {
let articleId = req.article._id;

User.findById(req.payload.id).then(user => {
if (!user) { return res.sendStatus(401); }

return user.favorite(articleId).then(() => {
return req.article.updateFavoriteCount().then(article => {
return res.json({article: article.toJSONFor(user)});
});
});
}).catch(next);
};

exports.unfavoriteArticleController = (req, res, next) => {
let articleId = req.article._id;

User.findById(req.payload.id).then( user => {
if (!user) { return res.sendStatus(401); }

return user.unfavorite(articleId).then(() => {
return req.article.updateFavoriteCount().then(article => {
return res.json({article: article.toJSONFor(user)});
});
});
}).catch(next);
};


exports.returnArticleCommentController = (req, res, next) =>{
Promise.resolve(req.payload ? User.findById(req.payload.id) : null).then(user => {
return req.article.populate({
path: 'comments',
populate: {
path: 'author'
},
options: {
sort: {
createdAt: 'desc'
}
}
}).execPopulate().then(article => {
return res.json({comments: req.article.comments.map(comment => {
return comment.toJSONFor(user);
})});
});
}).catch(next);
};


exports.createArticleCommentController = (req, res, next) => {
User.findById(req.payload.id).then(user => {
if(!user){ return res.sendStatus(401); }

const comment = new Comment(req.body.comment);
comment.article = req.article;
comment.author = user;

return comment.save().then(() => {
req.article.comments.push(comment);

return req.article.save().then(article => {
res.json({comment: comment.toJSONFor(user)});
});
});
}).catch(next);
};


exports.deleteArticleCommentController = (req, res, next) => {
if(req.comment.author.toString() === req.payload.id.toString()){
req.article.comments.remove(req.comment._id);
req.article.save()
.then(Comment.find({_id: req.comment._id}).remove().exec())
.then(() => {
res.sendStatus(204);
});
} else {
res.sendStatus(403);
}
};
39 changes: 39 additions & 0 deletions controllers/profiles.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
const mongoose = require('mongoose');
const User = mongoose.model('User');

exports.getUsernameController = (req, res, next) =>{
if(req.payload){
User.findById(req.payload.id).then(user =>{
if(!user){ return res.json({profile: req.profile.toProfileJSONFor(false)}); }

return res.json({profile: req.profile.toProfileJSONFor(user)});
});
} else {
return res.json({profile: req.profile.toProfileJSONFor(false)});
}
};


exports.getUsernameFollowController = (req, res, next) =>{
const profileId = req.profile._id;

User.findById(req.payload.id).then(user =>{
if (!user) { return res.sendStatus(401); }

return user.follow(profileId).then(() => {
return res.json({profile: req.profile.toProfileJSONFor(user)});
});
}).catch(next);
};

exports.deleteUsernameFollowController = (req, res, next) =>{
var profileId = req.profile._id;

User.findById(req.payload.id).then(user =>{
if (!user) { return res.sendStatus(401); }

return user.unfollow(profileId).then(() => {
return res.json({profile: req.profile.toProfileJSONFor(user)});
});
}).catch(next);
};
8 changes: 8 additions & 0 deletions controllers/tags.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
const mongoose = require('mongoose');
const Article = mongoose.model('Article');

exports.getTagsController = (req, res, next) => {
Article.find().distinct('tagList').then(tags => {
return res.json({tags: tags});
}).catch(next);
};
Loading