-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
335 lines (294 loc) Β· 12.2 KB
/
Copy pathserver.js
File metadata and controls
335 lines (294 loc) Β· 12.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
import express from 'express';
import cors from 'cors';
import dotenv from 'dotenv';
import path from 'path';
import { fileURLToPath } from 'url';
import authRoutes from './backend/routes/auth.routes.js';
import userRoutes from './backend/routes/user.routes.js';
import emailRoutes from './backend/routes/email.routes.js';
import flightRoutes from './backend/routes/flight.routes.js';
import hotelRoutes from './backend/routes/hotel.routes.js';
import supabase from './backend/config/supabase.js';
// Initialize environment variables
dotenv.config();
const app = express();
const PORT = process.env.PORT || 5001;
// Get directory name
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
// CORS configuration
const corsOptions = {
origin: true, // Allow all origins
credentials: true,
methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS', 'PATCH'],
allowedHeaders: ['Content-Type', 'Authorization', 'Accept', 'Origin', 'X-Requested-With'],
optionsSuccessStatus: 200,
exposedHeaders: ['set-cookie']
};
console.log('ddddddddddddddddddddddddd')
// Middleware
app.use(cors(corsOptions));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// Add headers for additional CORS support
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', req.headers.origin || '*');
res.setHeader('Access-Control-Allow-Credentials', 'true');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS, PATCH');
res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization, x-csrf-token');
res.setHeader('Access-Control-Expose-Headers', 'set-cookie');
// Handle preflight requests
if (req.method === 'OPTIONS') {
return res.status(200).end();
}
next();
});
// Global request debugging middleware
app.use((req, res, next) => {
console.log(`π₯ ${new Date().toISOString()} - ${req.method} ${req.originalUrl}`);
console.log(`π₯ Headers: ${JSON.stringify(req.headers)}`);
if (req.body && Object.keys(req.body).length > 0) {
console.log(`π₯ Body: ${JSON.stringify(req.body)}`);
}
next();
});
// Test Supabase connection
const testSupabaseConnection = async (retryCount = 0, maxRetries = 5) => {
try {
console.log(`π‘ Testing Supabase connection (attempt ${retryCount + 1}/${maxRetries + 1})...`);
const { data, error } = await supabase.from('users').select('count').single();
if (error) {
if (retryCount < maxRetries) {
console.warn(`β οΈ Supabase connection error: ${error.message}. Retrying in 3 seconds...`);
setTimeout(() => testSupabaseConnection(retryCount + 1, maxRetries), 3000);
return false;
} else {
console.error('β Failed to connect to Supabase after multiple attempts:', error.message);
console.log('The server will continue running, but database operations may fail.');
console.log('Possible issues:');
console.log(' - Supabase credentials in .env file may be incorrect');
console.log(' - Supabase service may be down or unreachable');
console.log(' - Required tables may not exist in your Supabase project');
console.log('You can use "node setup-supabase-tables.js" to create the required tables.');
return false;
}
}
console.log('β
Supabase connection established successfully.');
return true;
} catch (error) {
if (retryCount < maxRetries) {
console.warn(`β οΈ Error connecting to Supabase: ${error.message}. Retrying in 3 seconds...`);
setTimeout(() => testSupabaseConnection(retryCount + 1, maxRetries), 3000);
return false;
} else {
console.error('β Failed to connect to Supabase after multiple attempts:', error.message);
console.log('The server will continue running, but database operations may fail.');
return false;
}
}
};
// Initialize Supabase connection on startup
testSupabaseConnection();
// Routes
app.use('/api/auth', authRoutes);
app.use('/api/users', userRoutes);
app.use('/api/email', emailRoutes);
app.use('/api/flights', flightRoutes);
app.use('/api/hotels', hotelRoutes);
// Direct test email endpoint
app.post('/api/send-email', async (req, res) => {
try {
console.log('π§ Direct email endpoint hit with data:', req.body);
// Check if API key is available
if (!process.env.RESEND_API_KEY) {
console.error('π§ ERROR: Missing Resend API key in environment variables');
return res.status(500).json({
success: false,
error: 'Missing email API key'
});
}
// Import and initialize Resend with a try-catch to handle any errors
let resend;
try {
const { Resend } = await import('resend');
resend = new Resend(process.env.RESEND_API_KEY);
} catch (importError) {
console.error('π§ ERROR: Failed to initialize Resend:', importError);
return res.status(500).json({
success: false,
error: 'Failed to initialize email service'
});
}
const { name, email, phone, type = 'callback', details = {} } = req.body;
// Simple formatted email with dynamic content based on type
let html = `
<div style="font-family: Arial, sans-serif; padding: 20px; max-width: 600px; margin: 0 auto;">
<div style="background-color: #0066b2; padding: 20px; text-align: center; color: white;">
<h1>${type.toUpperCase()} Request Confirmation</h1>
</div>
<div style="padding: 20px; background-color: #f9f9f9;">
<p>Dear ${name},</p>
<p>Thank you for your ${type} request. We have received your information and will contact you shortly.</p>
<div style="background-color: white; padding: 15px; margin: 15px 0; border-radius: 5px;">
<h3>Your Request Details:</h3>
<p><strong>Name:</strong> ${name}</p>
<p><strong>Phone:</strong> ${phone}</p>
<p><strong>Email:</strong> ${email}</p>
`;
// Add type-specific content
if (type === 'package' && details) {
html += `
<h3>Package Information:</h3>
<p><strong>Package Name:</strong> ${details.packageName || 'Not specified'}</p>
<p><strong>Travel Date:</strong> ${details.travelDate || 'Not specified'}</p>
<p><strong>Number of Guests:</strong> ${details.guests || 'Not specified'}</p>
<p><strong>Budget:</strong> ${details.budget || 'Not specified'}</p>
<p><strong>Special Requests:</strong> ${details.request || 'None'}</p>
`;
} else if (type === 'rental' && details) {
html += `
<h3>Hotel Booking Information:</h3>
<p><strong>Hotel Name:</strong> ${details.hotelName || 'Not specified'}</p>
<p><strong>Check-in Date:</strong> ${details.checkIn || 'Not specified'}</p>
<p><strong>Check-out Date:</strong> ${details.checkOut || 'Not specified'}</p>
<p><strong>Number of Guests:</strong> ${details.guests || 'Not specified'}</p>
<p><strong>Room Type:</strong> ${details.roomType || 'Not specified'}</p>
<p><strong>Total Price:</strong> $${details.totalPrice || 'Not specified'}</p>
`;
} else if (type === 'cruise' && details) {
html += `
<h3>Cruise Information:</h3>
<p><strong>Preferred Time:</strong> ${details.preferredTime || 'Not specified'}</p>
<p><strong>Message:</strong> ${details.message || 'None'}</p>
`;
}
// Close the HTML structure
html += ` </div>
<p>Best regards,<br>The JetSetGo Team</p>
</div>
<div style="padding: 20px; text-align: center; font-size: 12px; color: #666; background-color: #f1f1f1;">
<p>This is an automated message, please do not reply to this email.</p>
<p>© 2025 JetSetGo. All rights reserved.</p>
</div>
</div>
`;
const text = html.replace(/<[^>]*>?/gm, '')
.replace(/\s+/g, ' ')
.trim();
try {
// Always use a verified sender email with Resend
const result = await resend.emails.send({
from: 'JetSetGo <onboarding@resend.dev>',
to: ['jetsetters721@gmail.com'], // Always send to the registered email
subject: `JetSetGo ${type.toUpperCase()} Request Confirmation`,
html,
text
});
console.log('π§ Email sent successfully:', result);
return res.status(200).json({
success: true,
message: 'Email sent successfully',
data: result
});
} catch (sendError) {
console.error('π§ Error sending email via Resend:', sendError);
// Return a more specific error message based on the error type
if (sendError.statusCode === 403 && sendError.message.includes('domain is not verified')) {
return res.status(200).json({
success: true,
message: 'Callback data saved, but email sending limited due to domain verification',
error: 'Domain not verified',
note: 'The callback request was saved successfully, but email sending requires domain verification. Your data is safely stored.'
});
}
return res.status(200).json({
success: true,
message: 'Callback data saved, but email could not be sent',
error: sendError.message || 'An error occurred sending email',
data: null
});
}
} catch (error) {
console.error('π§ Error in send-email endpoint:', error);
// Still return a 200 response to prevent blocking the callback flow
return res.status(200).json({
success: true,
message: 'Callback data saved, but email service encountered an error',
error: error.message || 'An error occurred processing the email request',
data: null
});
}
});
// Debug middleware for email routes
app.use('/api/email/*', (req, res, next) => {
console.log(`π Email route accessed: ${req.method} ${req.originalUrl}`);
console.log('π Request headers:', req.headers);
console.log('π Request body:', req.body);
next();
});
// Serve static files in production
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'));
});
}
// For local development
if (process.env.NODE_ENV !== 'production' || process.env.VERCEL_ENV === undefined) {
const findAvailablePort = async (startPort) => {
const maxPort = 65535;
let port = parseInt(startPort, 10);
while (port <= maxPort) {
try {
await new Promise((resolve, reject) => {
const server = app.listen(port)
.once('listening', () => {
server.close();
resolve();
})
.once('error', (err) => {
if (err.code === 'EADDRINUSE') {
reject(err);
} else {
reject(err);
}
});
});
return port;
} catch (err) {
if (err.code === 'EADDRINUSE') {
console.log(`β οΈ Port ${port} is in use, trying next port...`);
port++;
continue;
}
throw err;
}
}
throw new Error('No available ports found');
};
const startServer = async () => {
try {
const port = await findAvailablePort(PORT);
const server = app.listen(port, () => {
console.log(`π Server running on port ${port}`);
// Re-apply CORS middleware with updated settings
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', req.headers.origin || '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS,PATCH');
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Accept, Origin, X-Requested-With, x-csrf-token');
res.header('Access-Control-Allow-Credentials', 'true');
res.header('Access-Control-Expose-Headers', 'set-cookie');
if (req.method === 'OPTIONS') {
return res.sendStatus(200);
}
next();
});
});
} catch (error) {
console.error('β Failed to start server:', error);
process.exit(1);
}
};
startServer();}
// For Vercel serverless deployment
export default app;