-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
57 lines (47 loc) · 1.51 KB
/
index.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
import express from "express";
import path from "path";
import { MongoClient, ObjectId } from "mongodb";
import dotenv from "dotenv";
dotenv.config(); // Load environment variables from a .env file
const app = express();
const port = 4000;
app.use(express.static(path.resolve("public")));
// Connect to MongoDB
let db, users, stats;
(async () => {
try {
const client = await MongoClient.connect(process.env.MONGO_URL, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
db = client.db(); // Use the default database
users = db.collection("users");
stats = db.collection("stats");
console.log("Connected to MongoDB.");
} catch (error) {
console.error("Failed to connect to MongoDB:", error);
process.exit(1);
}
})();
// Set EJS as the templating engine
app.set("view engine", "ejs");
app.set("views", path.resolve("views")); // Ensure views are served from the correct directory
// Define the route
app.get("/:ticker", async (req, res) => {
const ticker = req.params.ticker;
try {
const user = await users.findOne({ ticker });
if (!user) {
return res.status(404).send("User not found.");
}
const userStats = await stats.findOne({ _id: new ObjectId(user._id) });
res.render("ticker", { user, stats: userStats });
} catch (error) {
console.error("Error fetching data:", error);
res.status(500).send("Internal server error.");
}
});
// Start the server
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});