Skip to content

Commit

Permalink
Add second version of the web app
Browse files Browse the repository at this point in the history
  • Loading branch information
MaiMee1 committed Apr 14, 2020
1 parent 2ea2583 commit 3312f86
Show file tree
Hide file tree
Showing 16 changed files with 1,514 additions and 0 deletions.
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -102,3 +102,7 @@ dist

# TernJS port file
.tern-port

# IDE configs
.idea
.vscode
46 changes: 46 additions & 0 deletions app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var indexRouter = require('./routes/index');

var app = express();

//Set up mongoose connection
var mongoose = require('mongoose');
var mongoDB = 'mongodb://localhost:27017';
mongoose.connect(mongoDB, { useNewUrlParser: true });
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'));

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});

// 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')('mongo-guessing-game: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);
}
119 changes: 119 additions & 0 deletions controllers/gameController.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
var Game = require('../models/game');

var async = require('async');
const validator = require('express-validator');

// Handle game play on GET.
exports.play_get = function (req, res, next) {
Game.findOne({}, function (err, game) {
if (err) { return next(err); }
if (game==null) { // No results.
res.redirect('/create');
}
res.render('play', { title: 'Guessing Game', error: err, game: game,
humanizedOrder: ['first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seventh', 'eight', 'ninth', 'tenth']
});
});
// res.render('play', {
// title: 'Guessing Game',
// choices: ['A', 'B', 'C', 'D'],
// answer: [],
// question: ['C', 'A', 'C', 'B'],
// humanizedOrder: ['first', 'second', 'third', 'fourth'],
// });
};

// Handle game play on POST.
exports.play_post = function (req, res, next) {
Game.findOne({}, function (err, game) {
if (err) { return next(err); }
// game logic
var doc = {};
if (req.body.choice === game.question[game.answer.length]) { // correct answer
console.log('correct answer');
doc = {'$set': { answer: game.answer.concat([req.body.choice]) }};
} else { // wrong answer
console.log('wrong answer');
doc = {'$set': { fails: game.fails + 1 }};
}
Game.findOneAndUpdate({ _id: game._id }, doc,{}
, function (err, game) {
if (err) { return next(err); }
if (game==null) { // No results.
var err = new Error('Game instance to update not found');
err.status = 200;
return next(err);
}
console.log('updated game ' + game);
res.redirect('/play');
});
});
};

// Handle Game create on GET.
exports.create_get = function (req, res, next) {
Game.findOne({}, function (err, game) {
if (err) { return next(err); }
res.render('create', { title: 'Create Guessing Game', game: game});
})
};

// Handle Game "create" on Post.
exports.create_post = [
validator.body('choices', )
.trim().notEmpty()
.withMessage('Choices are required'),
// TODO: Buggy
// Choices are unique
// .custom((value, { req }) => value.split("") === value.split("").filter((value, index, array) => array.indexOf(value)===index))
// .withMessage((value, { req }) => 'Choices must be unique'),
validator.body('question', 'Question is required')
.trim().notEmpty()
.withMessage('Question is required')
// Question can be answered with choices
.custom((value, { req }) => value.split("").every(val => req.body.choices.split("").includes(val)))
.withMessage('Question must be answerable by choices'),
// Process request after validation and sanitization.
(req, res, next) => {
console.log(req.body);
// Extract the validation errors from a request.
const errors = validator.validationResult(req);
const game = {
// Get unique elements in an array
choices: req.body.choices.split("").filter((value, index, array) => array.indexOf(value)===index),
question: req.body.question.split(""),
answer: [],
fails: 0,
};

if (!errors.isEmpty()) {
// There are errors. Render the form again with sanitized values/error messages.
res.render('create', {title: 'Create Guessing Game', game: game, errors: errors.array()});
} else {
// Creates the object if it doesn't exist.
Game.findOneAndUpdate({}, game, {upsert: true}
, function (err, old) {
if (err) {
return next(err);
}
console.log('updated game instance ' + old + ' with ' + game);
res.redirect('/play');
});
}
}
];

// Handle game restart on POST.
exports.restart_post = function (req, res, next) {
Game.findOneAndUpdate({}, {'$set': { fails: 0, answer: [] }}, { new: true }
, function (err, game) {
if (err) { return next(err); }
if (game==null) {
var err = new Error('Game instance not found');
err.status = 200;
return next(err);
}
console.log('updated game instance to be ', game);
res.redirect('/play');
});
};
20 changes: 20 additions & 0 deletions models/game.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
var mongoose = require('mongoose');

var Schema = mongoose.Schema;

var GameSchema = new Schema(
{
choices: [{type: String, required: true}],
question: [{type: String}],
answer: [{type: String}],
fails: {type: Number, required: true},
}
)

// Virtual for remaining character(s)
GameSchema.virtual('charsRemaining').get(function () {
return this.question.length - this.answer.length;
});

//Export model
module.exports = mongoose.model('Game', GameSchema);
Loading

0 comments on commit 3312f86

Please sign in to comment.