-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
82 lines (69 loc) · 2 KB
/
server.js
File metadata and controls
82 lines (69 loc) · 2 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
import express from 'express';
import dotenv from 'dotenv';
import {connectDB} from './config/db.js';
import cors from 'cors';
import mongoose from "mongoose";
dotenv.config();
const app = express();
const PORT = process.env.PORT || 3000;
app.use(cors());
app.use(express.json());
// Email Schema
const emailSchema = new mongoose.Schema({
email: {
type: String,
required: true,
unique: true,
lowercase: true,
trim: true,
match: [/^\S+@\S+\.\S+$/, 'Please enter a valid email']
},
createdAt: {
type: Date,
default: Date.now
}
});
const Email = mongoose.model('WaitlistEmails', emailSchema);
// API endpoint to subscribe email
app.post('/api/subscribe', async (req, res) => {
try {
const {email} = req.body;
if (!email) {
return res.status(400).json({error: 'Email is required'});
}
const newEmail = new Email({email});
await newEmail.save();
res.status(201).json({
message: 'Successfully subscribed!',
email: newEmail.email
});
} catch (error) {
if (error.code === 11000) {
return res.status(400).json({error: 'Email already subscribed'});
}
res.status(400).json({error: error.message});
}
});
// API endpoint to get all emails (for admin use)
app.get('/api/emails', async (req, res) => {
try {
const emails = await Email.find().sort({createdAt: -1});
res.json({count: emails.length, emails});
} catch (error) {
res.status(500).json({error: error.message});
}
});
// Start the server only after MongoDB connection
const startServer = async () => {
try {
await connectDB();
console.log('MongoDB connected successfully');
app.listen(PORT, () => {
console.log('Server started at http://localhost:' + PORT);
});
} catch (err) {
console.error('MongoDB connection failed:', err);
process.exit(1);
}
};
startServer();