-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
85 lines (70 loc) · 2.49 KB
/
app.js
File metadata and controls
85 lines (70 loc) · 2.49 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
// --- Core Modules ---
const express = require("express");
const cors = require("cors");
const { Pool } = require('pg');
const dotenv = require("dotenv");
dotenv.config();
// --- Third-Party Integrations ---
const stripe = require("stripe")(process.env.STRIPE_KEY);
// ------------------------------------------------------------------
// ⭐ 1. MOVE THIS SECTION UP! - App Setup and Middleware must come first
// ------------------------------------------------------------------
const app = express();
app.use(express.json());
// --- CORS Configuration (IMPORTANT) ---
const allowedOrigins = process.env.CORS_ORIGIN ? process.env.CORS_ORIGIN.split(',') : ['http://localhost:3000'];
app.use(cors({
origin: function (origin, callback) {
if (!origin) return callback(null, true);
if (allowedOrigins.indexOf(origin) === -1) {
const msg = 'The CORS policy for this site does not allow access from the specified Origin.';
return callback(new Error(msg), false);
}
return callback(null, true);
}
}));
// ------------------------------------------------------------------
// ⭐ 2. Database Connection - Can stay here or move up/down slightly
// ------------------------------------------------------------------
const pool = new Pool({
connectionString: process.env.DATABASE_URL,
ssl: {
rejectUnauthorized: false
}
});
// Test the connection on startup
pool.connect()
.then(client => {
console.log('PostgreSQL connected successfully!');
client.release();
})
.catch(err => console.error('PostgreSQL connection error:', err.stack));
// --- Test Route ---
app.get("/", (req, res) => {
res.status(200).json({
message: "Successfuly loaded! The server is running and database is connected.",
});
});
// --- Your Existing Stripe Payment Route ---
app.post("/payment/create", async (req, res) => {
const total = parseInt(req.query.total);
if (total > 0) {
const paymentIntent = await stripe.paymentIntents.create({
amount: total,
currency: "usd",
});
res.status(201).json({
clientSecret: paymentIntent.client_secret,
});
} else {
res.status(403).json({
message: "Total payment must be greater than zero"
});
}
});
// --- App Listen ---
const PORT = process.env.PORT || 3000;
app.listen(PORT, (err) => {
if (err) throw err;
console.log(`Server is running on http://localhost:${PORT}`);
});