-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
98 lines (77 loc) · 2.32 KB
/
app.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
const path = require('path');
const express = require("express");
const dotenv = require('dotenv');
const connectionToMongoDB= require('./config/db');
const morgan = require("morgan");
const methodOverride = require('method-override')
const exphbs = require('express-handlebars');
const passport = require('passport');
const session = require('express-session');
const MongoStore = require('connect-mongo')
//config setup
dotenv.config( {path: './config/config.env' })
//passport config
require('./config/passport')(passport)
// express as app and port setup
const app = express()
const PORT = process.env.PORT || 3000;
// static file rendering
app.use(express.static('public'))
//setup body parser with express
app.use(express.urlencoded({ extended: false}));
app.use(express.json())
// setup for methodOverride
// used to change the method on a particular piece of html
// e.g. changing a post to a put request etc.
app.use(methodOverride((req,res)=>{
if(req.body && typeof req.body === 'object' && '_method' in req.body){
let method = req.body._method;
delete req.body._method;
return method;
}
}))
//connection to MongoDB
connectionToMongoDB()
//setup for morgan outputs, but only in dev mode
if(process.env.NODE_ENV == 'development'){
app.use(morgan('dev'));
}
//Sessions middleware, must be above passport middleware in code
app.use(
session({
secret: 'anything',
resave: false,
saveUninitialized: false,
store: MongoStore.create({
mongoUrl: process.env.MONGODB_URI
})
}))
//passport middleware
app.use(passport.initialize());
app.use(passport.session());
// set up a global variable to read logged user
app.use((req,res,next)=>{
res.locals.user = req.user || null;
next();
})
// handlebars helpers
const { formatDate, stripTags, truncate, editIcon, select } = require('./helpers/hbs')
//Handlebars setup
app.engine('.hbs', exphbs.engine({
helpers: {
formatDate,
stripTags,
truncate,
editIcon,
select,
},
defaultLayout: 'main', extname: '.hbs'
}))
app.set('view engine', '.hbs')
//routes
app.use('/', require('./routes/index'))
app.use('/auth', require('./routes/auth'))
app.use('/notes', require('./routes/notes'))
app.listen(PORT, ()=> {
console.log(`Server running in ${process.env.NODE_ENV} mode on port ${PORT}`)
})