-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.js
65 lines (53 loc) · 1.56 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
63
64
65
const express = require("express");
const cors = require("cors");
const mongoose = require('mongoose');
require("dotenv").config({ path: "./config.env" });
// get driver connection
const dbo = require("./db/conn");
const app = express();
const port = process.env.PORT || 5000;
app.use(
cors({
origin: "*",
})
);
app.use(express.json());
// Include Swagger route at the base URL
app.use('/', require('./routes/swagger'));
// Other routes are included after the Swagger route
app.use(require("./routes/daos"));
app.use(require("./routes/polls"));
app.use(require("./routes/tokens"));
app.use(require("./routes/choices"));
app.use(require("./routes/aci"));
app.listen(port, async () => {
// perform a database connection when server starts
try {
dbo.connectToServer();
} catch (error) {
console.error(error);
}
console.log(`Server is running on port: ${port}`);
});
function getMongoDBDatabaseName(url) {
const dbNameMatch = url.match(/\/([^/?]+)(\?|$)/);
return dbNameMatch ? dbNameMatch[1] : null;
}
const connectToMongoDB = async () => {
try {
let connUrl = process.env.ATLAS_URI;
const database = getMongoDBDatabaseName(connUrl);
if (!database) {
const urlParts = connUrl.split('?');
connUrl = `${urlParts[0]}Lite?${urlParts[1] || ''}`;
}
console.log(connUrl);
await mongoose.connect(connUrl);
console.log('Connected to MongoDB using Mongoose');
} catch (error) {
console.error('Error connecting to MongoDB:', error);
process.exit(1);
}
};
// Call the function to connect to MongoDB
connectToMongoDB();