-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
100 lines (82 loc) · 2.5 KB
/
server.js
File metadata and controls
100 lines (82 loc) · 2.5 KB
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
99
100
const express = require("express");
const bodyParser = require("body-parser");
const morgan = require("morgan");
const path = require("path");
const mongoose = require("mongoose");
const cors = require("cors");
const logger = require("./src/utils/logger");
// ENV PORT
const { PORT, MONGO_URL, MONGO_OPTIONS, ENV } = require("./src/utils/config");
const PUBLIC_DIR = "src/public";
const app = express();
app.use(morgan("combined"));
app.use(
bodyParser.urlencoded({
extended: true
})
);
app.use(bodyParser.json());
const whitelist = [
"https://granularity-app.nihalwashere.xyz",
"https://granularity-web.nihalwashere.xyz",
"http://localhost:3000",
"http://localhost:3001"
];
app.use(
cors({
origin: (origin, callback) => {
// allow requests with no origin
// (like mobile apps or curl requests)
if (!origin) return callback(null, true);
if (whitelist.indexOf(origin) === -1) {
return callback(
new Error(
"The CORS policy for this site does not allow access from the specified Origin."
),
false
);
}
return callback(null, true);
}
})
);
// ROUTES
const users = require("./src/api/v1/users");
const forms = require("./src/api/v1/forms");
const responses = require("./src/api/v1/responses");
const insights = require("./src/api/v1/insights");
// USE ROUTES
app.use("/api/v1/users", users);
app.use("/api/v1/forms", forms);
app.use("/api/v1/responses", responses);
app.use("/api/v1/insights", insights);
// CONNECT TO MONGODB
mongoose
.connect(MONGO_URL, MONGO_OPTIONS)
.then(() => logger.info("MongoDB Connected!!!"))
.catch((err) => logger.error("MongoDB Connection Failed : ", err));
app.get("/", (req, res) =>
res.status(200).json({ success: true, message: "API is healthy." })
);
app.get("/logo_192.png", (req, res) => {
res.status(200).sendFile(path.join(__dirname, PUBLIC_DIR, "logo_192.png"));
});
app.get("/logo_512.png", (req, res) => {
res.status(200).sendFile(path.join(__dirname, PUBLIC_DIR, "logo_512.png"));
});
app.get("/embed.js", (req, res) => {
if (ENV === "PROD") {
return res
.status(200)
.sendFile(path.join(__dirname, PUBLIC_DIR, "embed.min.js"));
}
return res.status(200).sendFile(path.join(__dirname, PUBLIC_DIR, "embed.js"));
});
const server = app.listen(PORT, () => {
try {
logger.info(`App is now running on port ${PORT}!!!`);
} catch (error) {
logger.error("Failed to start server -> error : ", error);
}
});
module.exports = { app, server };