-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
75 lines (62 loc) · 1.94 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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import express from 'express';
import cors from 'cors';
import bodyParser from 'body-parser';
import fs from 'fs';
import { fileURLToPath, pathToFileURL } from 'url';
import path from 'path';
import { db } from './db.js';
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
const allowedOrigins = [
'http://localhost:3000', // For testing frontend
'http://localhost:8080', // For local backend access
'https://cartx.us', // Production frontend
];
const corsOptions = {
origin: (origin, callback) => {
// Allow requests with no origin (like from Postman)
if (!origin) return callback(null, true);
if (allowedOrigins.indexOf(origin) !== -1) {
callback(null, true);
} else {
callback(new Error('Not allowed by CORS'));
}
},
credentials: true,
optionsSuccessStatus: 200,
};
app.use(cors(corsOptions));
// Attach the database pool to the request object
app.use((req, res, next) => {
req.db = db;
next();
});
// Function to recursively import routes
const importRoutesFromDirectory = (directory) => {
fs.readdir(directory, { withFileTypes: true }, (err, files) => {
if (err) {
console.error('Could not list the directory.', err);
process.exit(1);
}
files.forEach((dirent) => {
const fullPath = path.join(directory, dirent.name);
if (dirent.isDirectory()) {
importRoutesFromDirectory(fullPath);
} else if (dirent.name.endsWith('.js')) {
const fileURL = pathToFileURL(fullPath).href;
import(fileURL).then((router) => {
app.use('/', router.default);
});
}
});
});
};
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const routesDirectory = path.join(__dirname, 'routes');
importRoutesFromDirectory(routesDirectory);
const port = 8080;
const server = app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});