-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
56 lines (44 loc) · 1.57 KB
/
server.js
File metadata and controls
56 lines (44 loc) · 1.57 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
import express from "express";
import mongoose from "mongoose";
import dotenv from "dotenv";
import path from "path";
import { fileURLToPath } from "url";
dotenv.config();
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const app = express();
app.use(express.json());
mongoose.connect(process.env.MONGODB_URI).then(() => {
console.log("Connected to MongoDB");
}).catch((err) => {
console.error("MongoDB connection error:", err.message);
});
const waitlistSchema = new mongoose.Schema({
email: { type: String, required: true, unique: true, lowercase: true, trim: true },
createdAt: { type: Date, default: Date.now },
});
const Waitlist = mongoose.model("Waitlist", waitlistSchema);
app.post("/api/waitlist", async (req, res) => {
const { email } = req.body;
if (!email || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
return res.status(400).json({ error: "Invalid email address" });
}
try {
await Waitlist.create({ email });
res.status(201).json({ message: "You're on the list!" });
} catch (err) {
if (err.code === 11000) {
return res.status(409).json({ error: "You're already on the list!" });
}
console.error(err);
res.status(500).json({ error: "Something went wrong" });
}
});
if (process.env.NODE_ENV === 'production') {
app.use(express.static(path.join(__dirname, 'dist')));
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'dist', 'index.html'));
});
}
const PORT = process.env.PORT || 3001;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));