Skip to content

Instantly share code, notes, and snippets.

@blackwright
Last active April 29, 2017 01:18
Show Gist options
  • Save blackwright/8cb4c70041f132b65d8f76985fa59ef8 to your computer and use it in GitHub Desktop.
Save blackwright/8cb4c70041f132b65d8f76985fa59ef8 to your computer and use it in GitHub Desktop.
Express Handlebars Template
const express = require('express');
const app = express();
// ----------------------------------------
// Dotenv
// ----------------------------------------
if (process.env.NODE_ENV !== "production") {
require("dotenv").config();
}
// ----------------------------------------
// Body Parser
// ----------------------------------------
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
// ----------------------------------------
// Flash Messages
// ----------------------------------------
const flash = require('express-flash-messages');
app.use(flash());
// ----------------------------------------
// Method Override
// ----------------------------------------
app.use((req, res, next) => {
let 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();
});
// ----------------------------------------
// Public
// ----------------------------------------
app.use(express.static(`${ __dirname }/public`));
// ----------------------------------------
// Mongoose
// ----------------------------------------
const mongoose = require('mongoose');
app.use((req, res, next) => {
if (mongoose.connection.readyState) {
next();
} else {
require('./mongo')().then(() => next());
}
});
// ----------------------------------------
// Logging
// ----------------------------------------
const morgan = require("morgan");
app.use(morgan("tiny"));
app.use((req, res, next) => {
console.log();
["query", "params", "body"].forEach(key => {
if (req[key]) {
const capKey = key[0].toUpperCase() + key.substr(1);
const value = JSON.stringify(req[key], null, 2);
console.log(`${capKey}: ${value}`);
}
});
next();
});
// ----------------------------------------
// Routes
// ----------------------------------------
const indexRouter = require('./routers/index');
app.use('/', indexRouter);
// ----------------------------------------
// Template Engine
// ----------------------------------------
const expressHandlebars = require('express-handlebars');
const helpers = require('./helpers');
const hbs = expressHandlebars.create({
helpers: helpers.registered,
extname: '.hbs',
partialsDir: 'views/',
defaultLayout: 'main'
});
app.engine('hbs', hbs.engine);
app.set('view engine', 'hbs');
// ----------------------------------------
// Server
// ----------------------------------------
const port = process.env.PORT ||
process.argv[2] ||
3000;
const host = 'localhost';
let args;
process.env.NODE_ENV === 'production' ?
args = [port] :
args = [port, host];
args.push(() => {
console.log(`Listening: http://${ host }:${ port }\n`);
});
// If we're running this file directly
// start up the server
if (require.main === module) {
app.listen.apply(app, args);
}
// ----------------------------------------
// Error Handling
// ----------------------------------------
app.use((err, req, res, next) => {
if (res.headersSent) {
return next(err);
}
if (err.stack) err = err.stack;
res.status(500).render('errors/500', { error: err });
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment