-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.ts
93 lines (73 loc) · 2.04 KB
/
app.ts
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
import express, { Express } from 'express';
import dotenv from 'dotenv';
import mongoose from 'mongoose';
import path from 'path';
import cookieParser from 'cookie-parser';
import logger from 'morgan';
import createError from 'http-errors';
import cors from 'cors';
import passport from 'passport';
import {
errorLogger,
errorResponder,
invalidPathHandler,
} from './lib/errorHandlers';
import apiRouter from './routes/api';
import authRouter from './routes/auth';
import corsOptions from './config/corsOptions';
import credentials from './lib/credentials';
dotenv.config();
// Import the entire Passport Local Strategy module
import './config/passportLocal';
// Import Passport JWT Strategy module
import passportJWT from './config/passportJWT';
passportJWT(passport);
/**
* ------------- GENERAL SETUP ----------------
*/
// Initialize express app
const app: Express = express();
// Set up Mongoose/MongoDb connection
const connectDB = async () => {
try {
await mongoose.connect(process.env.DB_CONNECTION_URL);
console.log('Connected to database');
} catch (error) {
if (error instanceof Error) {
console.error(error.message);
}
}
};
connectDB();
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')));
// Handle checking of credentials before CORS requests
// Also handle credentials requirement for cookies
app.use(credentials);
// Set up cors requests
app.use(cors(corsOptions));
// Initialize passport instance
app.use(passport.initialize());
/**
* ------------- ROUTES ----------------
*/
// Redirect to api route
app.get('/', (req, res) => {
res.redirect('/api');
});
app.use('/auth', authRouter);
app.use('/api', apiRouter);
// Catch 404 and forward to error handler
app.use((req, res, next) => {
next(createError(404));
});
// Log the error
app.use(errorLogger);
// Respond to the error
app.use(errorResponder);
// Send response for invalid paths
app.use(invalidPathHandler);
export default app;