-
Notifications
You must be signed in to change notification settings - Fork 49
/
app.js
91 lines (77 loc) · 2.33 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
/**
* Here, we will sync our database, create our application, and export this
* module so that we can use it in the bin directory, where we will be able to
* establish a server to listen and handle requests and responses;
*/
// Load environmental variables from .env file
require("dotenv").config();
const express = require("express");
const path = require("path");
const cookieParser = require("cookie-parser");
const logger = require("morgan");
const helmet = require("helmet");
const compression = require("compression");
// Utilities;
const createLocalDatabase = require("./utils/createLocalDatabase");
const seedDatabase = require("./utils/seedDatabase");
// Our database instance;
const db = require("./database");
// A helper function to sync our database;
const syncDatabase = () => {
if (process.env.NODE_ENV === "production") {
db.sync();
} else {
console.log("As a reminder, the forced synchronization option is on");
db.sync({ force: true })
.then(() => seedDatabase())
.catch((err) => {
if (err.name === "SequelizeConnectionError") {
createLocalDatabase();
seedDatabase();
} else {
console.log(err);
}
});
}
};
// Instantiate our express application;
const app = express();
// A helper function to create our app with configurations and middleware;
const configureApp = () => {
app.use(helmet());
app.use(logger("dev"));
// handle request data:
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(compression());
app.use(cookieParser());
// Our apiRouter
const apiRouter = require("./routes/index");
// Mount our apiRouter
app.use("/api", apiRouter);
// Error handling;
app.use((req, res, next) => {
if (path.extname(req.path).length) {
const err = new Error("Not found");
err.status = 404;
next(err);
} else {
next();
}
});
// More error handling;
app.use((err, req, res, next) => {
console.error(err);
console.error(err.stack);
res.status(err.status || 500).send(err.message || "Internal server error.");
});
};
// Main function declaration;
const bootApp = async () => {
await syncDatabase();
await configureApp();
};
// Main function invocation;
bootApp();
// Export our app, so that it can be imported in the www file;
module.exports = app;