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

. #14

Open
wants to merge 14 commits into
base: master
Choose a base branch
from
Open

. #14

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
136 changes: 136 additions & 0 deletions app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
var express = require("express");
var app = express();

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

// ----------------------------------------
// Sessions/Cookies
// ----------------------------------------
var cookieSession = require("cookie-session");

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

app.use((req, res, next) => {
res.locals.session = req.session;
res.locals.currentUser = req.session.currentUser;
next();
});

// ----------------------------------------
// Method Override
// ----------------------------------------
app.use((req, res, next) => {
var method;
if (req.query._method) {
method = req.query._method;
delete req.query._method;
for (let key in req.query) {
req.body[key] = decodeURIComponent(req.query[key]);
}
} else if (typeof req.body === "object" && req.body._method) {
method = req.body._method;
delete req.body._method;
}

if (method) {
method = method.toUpperCase();
req.method = method;
}

next();
});

// ----------------------------------------
// Referrer
// ----------------------------------------
app.use((req, res, next) => {
req.session.backUrl = req.header("Referer") || "/";
next();
});

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

// ----------------------------------------
// Logging
// ----------------------------------------
var morgan = require("morgan");
app.use(morgan("tiny"));
app.use((req, res, next) => {
["query", "params", "body"].forEach(key => {
if (req[key]) {
var capKey = key[0].toUpperCase() + key.substr(1);
var value = JSON.stringify(req[key], null, 2);
console.log(`${capKey}: ${value}`);
}
});
next();
});

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

// ----------------------------------------
// Routes
// ----------------------------------------
var sessionsRouter = require("./routers/sessions");
app.use("/", sessionsRouter);

var usersRouter = require("./routers/users");
app.use("/users", usersRouter);

var postsRouter = require("./routers/posts");
app.use("/posts", postsRouter);

// var ratablesRouter = require('./routers/ratables');
// app.use('/ratables', ratablesRouter);

// ----------------------------------------
// Template Engine
// ----------------------------------------
var expressHandlebars = require("express-handlebars");

var hbs = expressHandlebars.create({
partialsDir: "views/",
defaultLayout: "main"
});

app.engine("handlebars", hbs.engine);
app.set("view engine", "handlebars");

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

var args;
process.env.NODE_ENV === "production" ? (args = [port]) : (args = [port, host]);

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

app.listen.apply(app, args);

module.exports = app;
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"
}
}
14 changes: 14 additions & 0 deletions models/comment.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
var mongoose = require("mongoose");
var Schema = mongoose.Schema;
var Commentable = require("./commentable");

let CommentSchema = new Schema(
{},
{
discriminatorKey: "kind"
}
);

const Comment = Commentable.discriminator("Comment", CommentSchema);

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

let CommentableSchema = new Schema(
{
body: String,
score: Number,
author: {
type: Schema.Types.ObjectId,
ref: "User"
},
comments: [
{
type: Schema.Types.ObjectId,
ref: "Comment"
}
]
},
{
timestamps: true,
discriminatorKey: "kind"
}
);

const Commentable = mongoose.model("Commentable", CommentableSchema);

module.exports = Commentable;
18 changes: 18 additions & 0 deletions models/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
var mongoose = require("mongoose");
var bluebird = require("bluebird");

// Set bluebird as the promise
// library for mongoose
mongoose.Promise = bluebird;

var models = {};

// Load models and attach to models here
models.User = require("./user");
models.Commentable = require("./commentable");
models.Comment = require("./comment");
models.Post = require("./post");

//... more models

module.exports = models;
16 changes: 16 additions & 0 deletions models/post.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
var mongoose = require("mongoose");
var Schema = mongoose.Schema;
var Commentable = require("./commentable");

let PostSchema = new Schema(
{
title: String
},
{
discriminatorKey: "kind"
}
);

const Post = Commentable.discriminator("Post", PostSchema);

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

var UserSchema = new Schema(
{
fname: String,
lname: String,
username: String,
email: String
},
{
timestamps: true
}
);

// UserSchema.methods.name = function() {
// return `${ this.fname } ${ this.lname }`;
// };

// UserSchema.statics.findByFirstName = function (fname) {
// return User.find({ fname: fname });
// };

// UserSchema.virtual('fullname').set(function(name) {
// console.log('Setting the name of the user');
// name = name.toString();
// var splat = name.split(' ');
// var fname = splat[0] || this.fname;
// var lname = splat[1] || this.lname;
// this.fname = fname;
// this.lname = lname;
// return this.name;
// });

var User = mongoose.model("User", UserSchema);

module.exports = User;
10 changes: 10 additions & 0 deletions mongo.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
var mongoose = require("mongoose");
var env = process.env.NODE_ENV || "development";
var config = require("./config/mongo")[env];

module.exports = () => {
var envUrl = process.env[config.use_env_variable];
var localUrl = `mongodb://${config.host}/${config.database}`;
var mongoUrl = envUrl ? envUrl : localUrl;
return mongoose.connect(mongoUrl);
};
33 changes: 33 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
{
"name": "assignment_thorredit",
"version": "1.0.0",
"description": "A social news web application for Viking thunder Gods",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "nodemon app.js",
"c": "node repl.js",
"seed": "node seeds",
"seeds": "node seeds"
},
"repository": {
"type": "git",
"url": "git+https://github.com/eglital/assignment_thorredit.git"
},
"author": "",
"license": "ISC",
"bugs": {
"url": "https://github.com/eglital/assignment_thorredit/issues"
},
"homepage": "https://github.com/eglital/assignment_thorredit#readme",
"dependencies": {
"bluebird": "^3.5.0",
"body-parser": "^1.17.1",
"cookie-session": "^2.0.0-beta.1",
"express": "^4.15.2",
"express-handlebars": "^3.0.0",
"faker": "^4.1.0",
"mongoose": "^4.9.5",
"morgan": "^1.8.1"
}
}
13 changes: 13 additions & 0 deletions repl.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
var mongoose = require("mongoose");
var repl = require("repl").start({});
var models = require("./models");

require("./mongo")().then(() => {
repl.context.models = models;

Object.keys(models).forEach(modelName => {
repl.context[modelName] = mongoose.model(modelName);
});

repl.context.lg = data => console.log(data);
});
59 changes: 59 additions & 0 deletions routers/posts.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
var express = require("express");
var router = express.Router();
var mongoose = require("mongoose");
var models = require("./../models");
var User = mongoose.model("User");
var Post = mongoose.model("Post");

// ----------------------------------------
// Index
// ----------------------------------------
router.get("/", (req, res) => {
if (req.session.currentUser) {
var posts;
Post.find({})
.then(postsProm => {
posts = postsProm;
var promiseArr = [];
posts.forEach(post => {
promiseArr.push(User.findById(post.author));
});
return Promise.all(promiseArr);
})
.then(users => {
posts.forEach(post => {
users.forEach(user => {
//console.log("user " + user + "\n" + "post " + post);
if (post.author == user.id) {
console.log("inside if statement .......");
post.user = user;
}
});
});
res.render("posts/index", { posts });
})
.catch(e => res.status(500).send(e.stack));
} else {
res.redirect("/login");
}
});

router.get("/:id", (req, res) => {
Post.findOne({ _id: req.params.id })
.populate({
path: "comments author",
populate: {
path: "comments author",
populate: {
path: "author"
}
}
})
.then(post => {
console.log("inside router.get ", post);
res.render("posts/show", { post });
})
.catch(e => res.status(500).send(e.stack));
});

module.exports = router;
Loading