-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathserver.js
62 lines (50 loc) · 1.59 KB
/
server.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
const dotenv = require("dotenv");
const routes = require("./app/routes");
const mongoose = require("mongoose");
const express = require("express");
const fileUpload = require("express-fileupload");
const cors = require('cors')
dotenv.config({ path: "./.env" });
class Server {
constructor(dbName) {
this.app = express();
this.serverPort = process.env.PORT || 4000;
this.dbName = dbName || process.env.DB_NAME;
this.mongoConnection;
this._server;
this.connectToDB();
this.useMiddlewares();
this.getRoutes();
this.start();
}
async connectToDB() {
const dbConnectionString = `mongodb+srv://${process.env.DB_USER}:${process.env.DB_PASSWD}@awesomedb.lli4m.mongodb.net/${this.dbName}?retryWrites=true&w=majority`;
try {
this.mongoConnection = await mongoose.connect(dbConnectionString, {
useNewUrlParser: true,
useUnifiedTopology: true
});
} catch (error) {
console.log(error);
console.log("Connection to database failed. Try again...");
}
}
useMiddlewares() {
this.app.use(express.json());
this.app.use(fileUpload());
this.app.use(cors());
}
getRoutes() {
routes(this.app);
}
start() {
this._server = this.app.listen(this.serverPort, () => {
console.log("MovieMatch listens on port " + this.serverPort);
});
}
close() {
this.mongoConnection.connection.close();
this._server.close();
}
}
module.exports = Server;