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

initial #21

Open
wants to merge 9 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/
105 changes: 105 additions & 0 deletions app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
var express = require("express");
var path = require("path");
var favicon = require("serve-favicon");
var logger = require("morgan");
var cookieParser = require("cookie-parser");
var bodyParser = require("body-parser");
var session = require("express-session");

var index = require("./routes/index");
var users = require("./routes/users");
var posts = require("./routes/post");
var comments = require("./routes/comment");

var login = require("./routes/login");
var app = express();

//middleware to connect to MongoDB via mongoose in your `app.js`
var mongoose = require("mongoose");
app.use((req, res, next) => {
if (mongoose.connection.readyState) {
next();
} else {
require("./mongo")().then(() => next());
}
});

// view engine setup
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "hbs");

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger("dev"));
app.use(
bodyParser.urlencoded({
extended: true
})
);
app.use(cookieParser());
app.use(express.static(path.join(__dirname, "public")));

// --------------------------------------
// Method Override
// --------------------------------------
const methodOverride = require("method-override");
const getPostSupport = require("express-method-override-get-post-support");

app.use(
methodOverride(
getPostSupport.callback,
getPostSupport.options // { methods: ['POST', 'GET'] }
)
);

app.use(
session({
secret: "keyboard cat",
resave: true,
saveUninitialized: true,
cookie: {
secure: false
} //our website is not secure
})
);

const morgan = require("morgan");
const morganToolkit = require("morgan-toolkit")(morgan);

app.use(morganToolkit());

app.use("/login", login);

app.use(function(req, res, next) {
if (!req.cookies.userId && req.path != "/login") {
req.path = "/login";
res.redirect("/login");
} else {
next();
}
});

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

// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error("Not Found");
err.status = 404;
next(err);
});

// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get("env") === "development" ? err : {};

// render the error page
res.status(err.status || 500);
res.render("error");
});

module.exports = app;
90 changes: 90 additions & 0 deletions bin/www
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
#!/usr/bin/env node

/**
* Module dependencies.
*/

var app = require('../app');
var debug = require('debug')('assignment-thoreddit:server');
var http = require('http');

/**
* Get port from environment and store in Express.
*/

var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);

/**
* Create HTTP server.
*/

var server = http.createServer(app);

/**
* Listen on provided port, on all network interfaces.
*/

server.listen(port);
server.on('error', onError);
server.on('listening', onListening);

/**
* Normalize a port into a number, string, or false.
*/

function normalizePort(val) {
var port = parseInt(val, 10);

if (isNaN(port)) {
// named pipe
return val;
}

if (port >= 0) {
// port number
return port;
}

return false;
}

/**
* Event listener for HTTP server "error" event.
*/

function onError(error) {
if (error.syscall !== 'listen') {
throw error;
}

var bind = typeof port === 'string'
? 'Pipe ' + port
: 'Port ' + port;

// handle specific listen errors with friendly messages
switch (error.code) {
case 'EACCES':
console.error(bind + ' requires elevated privileges');
process.exit(1);
break;
case 'EADDRINUSE':
console.error(bind + ' is already in use');
process.exit(1);
break;
default:
throw error;
}
}

/**
* Event listener for HTTP server "listening" event.
*/

function onListening() {
var addr = server.address();
var bind = typeof addr === 'string'
? 'pipe ' + addr
: 'port ' + addr.port;
debug('Listening on ' + bind);
}
16 changes: 16 additions & 0 deletions config/mongo.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
{
"development":
{
"database": "thoreddit_development",
"host": "localhost"
},
"test":
{
"database": "thoreddit_test",
"host": "localhost"
},
"production":
{
"use_env_variable": "MONGODB_URI"
}
}
15 changes: 15 additions & 0 deletions models/comment.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

const Commentable = require('./commentable.js');
var CommentSchema = new Schema({
parent: {
type: Schema.Types.ObjectId,
ref: 'Commentable'
}
}, {
discriminatorKey: 'kind'
});

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

var CommentableSchema = new Schema(
{
author: {
type: Schema.Types.ObjectId,
ref: "User"
},
body: String,
children: [
{
type: Schema.Types.ObjectId,
ref: "Commentable"
}
]
},
{
timestamps: true,
discriminatorKey: "kind"
}
);

var 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.Post = require("./post");
models.Comment = require("./comment");
models.Commentable = require("./commentable");
//... more models

module.exports = models;

13 changes: 13 additions & 0 deletions models/post.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

const Commentable = require('./commentable.js');

var PostSchema = new Schema({
title: String
}, {
discriminatorKey: 'kind'
});

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


var UserSchema = new Schema({
username: String,
email: String

}, {
timestamps: true
});

// Create the model with a defined schema
var User = mongoose.model('User', UserSchema);

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

const Commentable = require('./commentable.js');

var VoteSchema = new Schema({
user: { type: Schema.Types.ObjectId, ref: 'User' }, //just have user vote once. Query vote collection for already submitted user
votetype: Number,
commentable: {
type: Schema.Types.ObjectId,
ref: 'Commentable'
}
}, {
discriminatorKey: 'kind'
});

var Vote = Commentable.discriminator('Vote', VoteSchema);
module.exports = Vote;
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);
};
Loading