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

Thor read it #9

Open
wants to merge 20 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
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
node_modules
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,4 @@
# assignment_thoreddit
A social news web application for Viking thunder Gods

Benny and Will
65 changes: 65 additions & 0 deletions app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
const express = require("express");
const app = express();

// Templates
const expressHandlebars = require("express-handlebars");
const hbs = expressHandlebars.create({
partialsDir: "views/",
defaultLayout: "application",
helpers: require("./helpers")
});
app.engine("handlebars", hbs.engine);
app.set("view engine", "handlebars");

// Post Data
const bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ extended: true }));

// Session
const cookieSession = require("cookie-session");
app.use(
cookieSession({
name: "session",
keys: ["asdf90890sdfa980sdf98a"]
})
);

// Flash
const flash = require("express-flash-messages");
app.use(flash());

// Log Request Info
const morgan = require("morgan");
const morganToolkit = require("morgan-toolkit")(morgan);
app.use(morganToolkit());

// Method Overriding
const methodOverride = require("method-override");
const getPostSupport = require("express-method-override-get-post-support");
app.use(methodOverride(getPostSupport.callback, getPostSupport.options));

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

// Routes
app.use("/posts", require("./routers/posts"));
app.all("/", (req, res) => res.redirect("/posts"));
app.use("/users", require("./routers/users"));
app.use("/comments", require("./routers/comments"));

// Set up port/host
const port = process.env.PORT || process.argv[2] || 3000;
const host = "localhost";
let args = process.env.NODE_ENV === "production" ? [port] : [port, host];

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

// Use apply to pass the args to listen
app.listen.apply(app, args);
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_dev",
"host": "localhost"
},
"test": {
"database": "",
"host": "localhost"
},
"production": {
"use_env_variable": "MONGODB_URI"
}
}
6 changes: 6 additions & 0 deletions config/mongoUrl.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
const env = process.env.NODE_ENV || "development";
const config = require("./mongo.json")[env];
module.exports =
process.env.NODE_ENV === "production"
? process.env[config.use_env_variable]
: `mongodb://${config.host}/${config.database}`;
7 changes: 7 additions & 0 deletions helpers/CommentHelper.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
module.exports = {
commentsPath: () => "/comments",
commentPath: id => `/comments/${id}`,
newCommentPath: () => "/comments/new",
editCommentPath: id => `/comments/${id}/edit`,
destroyCommentPath: id => `/comments/${id}/?_method=delete`
};
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;
7 changes: 7 additions & 0 deletions helpers/PostHelper.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
module.exports = {
postsPath: () => "/posts",
postPath: id => `/posts/${id}`,
newPostPath: () => "/posts/new",
editPostPath: id => `/posts/${id}/edit`,
destroyPostPath: id => `/posts/${id}/?_method=delete`
};
7 changes: 7 additions & 0 deletions helpers/UserHelper.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
module.exports = {
usersPath: () => "/users",
userPath: id => `/users/${id}`,
newUserPath: () => "/users/new",
editUserPath: id => `/users/${id}/edit`,
destroyUserPath: id => `/users/${id}/?_method=delete`
};
5 changes: 5 additions & 0 deletions helpers/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
const LoadHelpers = require("load-helpers");
const helperLoader = new LoadHelpers();
const helpers = helperLoader.load("helpers/*Helper.js").cache;

module.exports = helpers;
76 changes: 76 additions & 0 deletions models/Comment.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
const mongoose = require("mongoose");
const Scorable = require("./Scorable");
const Schema = mongoose.Schema;

const CommentSchema = new Schema(
{
post: { type: Schema.Types.ObjectId, ref: "Post" },
user: { type: Schema.Types.ObjectId, ref: "User" },
body: String
},
{
discriminatorKey: "scorableKind"
}
);

CommentSchema.virtual("summary").get(function() {
return this.body.slice(0, 100) + "...";
});

CommentSchema.statics.new = function(params) {
return this.create({
body: params.body,
user: params.userId,
post: params.postId
});
};

CommentSchema.post("save", function() {
mongoose
.model("User")
.update(
{ _id: this.user },
{ $pull: { comments: this._id } },
{ multi: true }
)
.exec();
mongoose
.model("User")
.update({ _id: this.user }, { $push: { comments: this._id } })
.exec();
mongoose
.model("Post")
.update(
{ _id: this.post },
{ $pull: { comments: this._id } },
{ multi: true }
)
.exec();
mongoose
.model("Post")
.update({ _id: this.post }, { $push: { comments: this._id } })
.exec();
});

CommentSchema.pre("remove", function(next) {
mongoose
.model("User")
.update(
{ _id: this.user },
{ $pull: { comments: this._id } },
{ multi: true }
)
.exec();
mongoose
.model("Post")
.update(
{ _id: this.post },
{ $pull: { comments: this._id } },
{ multi: true }
)
.exec();
next();
});

let Comment = Scorable.discriminator("Comment", CommentSchema);
module.exports = Comment;
63 changes: 63 additions & 0 deletions models/Post.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
const mongoose = require("mongoose");
const Scorable = require("./Scorable");
const Schema = mongoose.Schema;

const PostSchema = new Schema(
{
body: String,
title: String,
user: { type: Schema.Types.ObjectId, ref: "User" },
comments: [{ type: Schema.Types.ObjectId, ref: "Comment" }]
},
{
discriminatorKey: "scorableKind"
}
);

PostSchema.statics.getAll = function() {
return this.find({}, {}, { sort: { createdAt: -1 } }).populate("user");
};

PostSchema.statics.getById = function(id) {
return this.findById(id).populate("user").populate({
path: "comments",
populate: { path: "user", model: "User" },
options: { sort: { createdAt: -1 } }
});
};

PostSchema.statics.new = function(params) {
return this.create({
title: params.title,
body: params.body,
user: params.userId
});
};

PostSchema.post("save", function() {
mongoose
.model("User")
.update({ _id: this.user }, { $pull: { posts: this._id } }, { multi: true })
.exec();
mongoose
.model("User")
.update({ _id: this.user }, { $push: { posts: this._id } })
.exec();
});

PostSchema.pre("remove", function(next) {
mongoose
.model("User")
.update(
{ posts: this._id },
{ $pull: { posts: this._id } },
{ multi: true }
)
.exec();
mongoose.model("Comment").remove({ post: this._id }).exec();
next();
});

let Post = Scorable.discriminator("Post", PostSchema);

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

const ScorableSchema = new Schema(
{
score: Number
},
{
timestamps: true,
discriminatorKey: "scorableKind"
}
);

ScorableSchema.methods.upvote = function() {
return (this.score += 1);
};

ScorableSchema.methods.downvote = function() {
return (this.score -= 1);
};

let Scorable = mongoose.model("Scorable", ScorableSchema);
module.exports = Scorable;
39 changes: 39 additions & 0 deletions models/User.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
const mongoose = require("mongoose");
const Schema = mongoose.Schema;

const UserSchema = new Schema(
{
username: String,
email: String,
posts: [{ type: Schema.Types.ObjectId, ref: "Post" }],
comments: [{ type: Schema.Types.ObjectId, ref: "Comment" }]
},
{
timestamps: true
}
);

UserSchema.statics.getAll = function() {
return this.find({}, {}, { sort: { createdAt: -1 } })
.populate({ path: "comments", options: { sort: { createdAt: -1 } } })
.populate({ path: "posts", options: { sort: { createdAt: -1 } } });
};

UserSchema.statics.getById = function(id) {
return this.findById(id)
.populate({ path: "comments", options: { sort: { createdAt: -1 } } })
.populate({ path: "posts", options: { sort: { createdAt: -1 } } });
};

UserSchema.statics.new = function(params) {
return this.create({ username: params.username, email: params.email });
};

UserSchema.pre("remove", function(next) {
mongoose.model("Post").remove({ user: this._id }).exec();
mongoose.model("Comment").remove({ user: this._id }).exec();
next();
});

let User = mongoose.model("User", UserSchema);
module.exports = User;
10 changes: 10 additions & 0 deletions models/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
const mongoose = require("mongoose");
const bluebird = require("bluebird");

mongoose.Promise = bluebird;

module.exports = {
Comment: require("./Comment"),
Post: require("./Post"),
User: require("./User")
};
5 changes: 5 additions & 0 deletions mongo.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
const mongoose = require("mongoose");

module.exports = () => {
return mongoose.connect(require("./config/mongoUrl"));
};
Loading