Huzaifa1313 commited on
Commit
923720c
Β·
verified Β·
1 Parent(s): cbbb3a0

Update server.js

Browse files
Files changed (1) hide show
  1. server.js +23 -8
server.js CHANGED
@@ -10,16 +10,17 @@ const multer = require('multer');
10
  const Datastore = require('@seald-io/nedb');
11
  const { MongoClient, ObjectId } = require('mongodb');
12
 
 
13
  dotenv.config({ path: path.join(__dirname, '.env') });
14
  dotenv.config({ path: path.join(__dirname, '..', '.env') });
15
 
16
  const app = express();
17
- const PORT = Number(process.env.PORT || 3001);
18
  const JWT_SECRET = process.env.JWT_SECRET || 'hitech_secret_2025';
19
  const MONGODB_URI = process.env.MONGODB_URI;
20
  const MONGODB_DB = process.env.MONGODB_DB || 'hitech_technologies';
21
 
22
- const ROOT_DIR = path.join(__dirname, '..');
23
  const PUBLIC_DIR = path.join(ROOT_DIR, 'public');
24
  const UPLOADS_DIR = path.join(ROOT_DIR, 'uploads');
25
  const LEGACY_DATA_DIR = path.join(ROOT_DIR, 'data');
@@ -195,28 +196,39 @@ async function migrateLegacyCollection(collectionName, filePath, mapper = legacy
195
  async function bootstrapDatabase() {
196
  ensureDirs();
197
  if (!MONGODB_URI) {
198
- throw new Error('MONGODB_URI is missing. Put it in hitech-mongodb/.env');
199
  }
200
 
 
 
201
  const connectOptions = {
202
- serverSelectionTimeoutMS: 10000,
 
 
 
203
  };
204
 
205
  const tryConnect = async () => {
206
  mongoClient = new MongoClient(MONGODB_URI, connectOptions);
207
  await mongoClient.connect();
208
  mongoDb = mongoClient.db(MONGODB_DB);
 
209
  };
210
 
211
  try {
212
  await tryConnect();
213
  } catch (error) {
 
 
214
  const isSrvUri = MONGODB_URI.startsWith('mongodb+srv://');
215
- const isSrvLookupError = String(error?.message || '').includes('querySrv') || String(error?.code || '').includes('ECONNREFUSED');
 
 
216
  if (isSrvUri && isSrvLookupError) {
 
217
  dns.setServers(['1.1.1.1', '8.8.8.8']);
218
  await tryConnect();
219
- console.log('MongoDB connected after switching DNS resolvers to 1.1.1.1 / 8.8.8.8');
220
  } else {
221
  throw error;
222
  }
@@ -521,9 +533,11 @@ app.get('/api/health', asyncHandler(async (req, res) => {
521
  });
522
  }));
523
 
 
524
  app.get('/admin', (req, res) => res.sendFile(path.join(PUBLIC_DIR, 'admin.html')));
525
  app.get('*', (req, res) => res.sendFile(path.join(PUBLIC_DIR, 'index.html')));
526
 
 
527
  app.use((err, req, res, next) => {
528
  console.error(err);
529
  if (err && err.message === 'Images only') {
@@ -532,9 +546,10 @@ app.use((err, req, res, next) => {
532
  res.status(500).json({ error: err?.message || 'Server error' });
533
  });
534
 
 
535
  bootstrapDatabase()
536
  .then(() => {
537
- app.listen(PORT, () => {
538
  console.log(`\nπŸš€ HiTech Technologies (MongoDB) - http://localhost:${PORT}`);
539
  console.log(`πŸ”‘ Admin Panel - http://localhost:${PORT}/admin`);
540
  console.log(`πŸ“¦ MongoDB DB - ${MONGODB_DB}`);
@@ -543,4 +558,4 @@ bootstrapDatabase()
543
  .catch((error) => {
544
  console.error('Failed to bootstrap application:', error);
545
  process.exit(1);
546
- });
 
10
  const Datastore = require('@seald-io/nedb');
11
  const { MongoClient, ObjectId } = require('mongodb');
12
 
13
+ // Load environment variables
14
  dotenv.config({ path: path.join(__dirname, '.env') });
15
  dotenv.config({ path: path.join(__dirname, '..', '.env') });
16
 
17
  const app = express();
18
+ const PORT = Number(process.env.PORT || 7860); // Hugging Face default port
19
  const JWT_SECRET = process.env.JWT_SECRET || 'hitech_secret_2025';
20
  const MONGODB_URI = process.env.MONGODB_URI;
21
  const MONGODB_DB = process.env.MONGODB_DB || 'hitech_technologies';
22
 
23
+ const ROOT_DIR = __dirname; // Fixed for Hugging Face
24
  const PUBLIC_DIR = path.join(ROOT_DIR, 'public');
25
  const UPLOADS_DIR = path.join(ROOT_DIR, 'uploads');
26
  const LEGACY_DATA_DIR = path.join(ROOT_DIR, 'data');
 
196
  async function bootstrapDatabase() {
197
  ensureDirs();
198
  if (!MONGODB_URI) {
199
+ throw new Error('MONGODB_URI is missing. Put it in .env or Hugging Face secret');
200
  }
201
 
202
+ console.log('MongoDB URI exists, attempting connection...');
203
+
204
  const connectOptions = {
205
+ serverSelectionTimeoutMS: 30000,
206
+ socketTimeoutMS: 45000,
207
+ connectTimeoutMS: 30000,
208
+ family: 4, // Force IPv4 - important for Hugging Face
209
  };
210
 
211
  const tryConnect = async () => {
212
  mongoClient = new MongoClient(MONGODB_URI, connectOptions);
213
  await mongoClient.connect();
214
  mongoDb = mongoClient.db(MONGODB_DB);
215
+ console.log('βœ… MongoDB Connected Successfully!');
216
  };
217
 
218
  try {
219
  await tryConnect();
220
  } catch (error) {
221
+ console.error('First connection attempt failed:', error.message);
222
+
223
  const isSrvUri = MONGODB_URI.startsWith('mongodb+srv://');
224
+ const isSrvLookupError = String(error?.message || '').includes('querySrv') ||
225
+ String(error?.code || '').includes('ECONNREFUSED');
226
+
227
  if (isSrvUri && isSrvLookupError) {
228
+ console.log('Attempting with DNS servers 1.1.1.1, 8.8.8.8...');
229
  dns.setServers(['1.1.1.1', '8.8.8.8']);
230
  await tryConnect();
231
+ console.log('MongoDB connected after switching DNS resolvers');
232
  } else {
233
  throw error;
234
  }
 
533
  });
534
  }));
535
 
536
+ // Serve admin panel and frontend
537
  app.get('/admin', (req, res) => res.sendFile(path.join(PUBLIC_DIR, 'admin.html')));
538
  app.get('*', (req, res) => res.sendFile(path.join(PUBLIC_DIR, 'index.html')));
539
 
540
+ // Error handler
541
  app.use((err, req, res, next) => {
542
  console.error(err);
543
  if (err && err.message === 'Images only') {
 
546
  res.status(500).json({ error: err?.message || 'Server error' });
547
  });
548
 
549
+ // Start server
550
  bootstrapDatabase()
551
  .then(() => {
552
+ app.listen(PORT, '0.0.0.0', () => {
553
  console.log(`\nπŸš€ HiTech Technologies (MongoDB) - http://localhost:${PORT}`);
554
  console.log(`πŸ”‘ Admin Panel - http://localhost:${PORT}/admin`);
555
  console.log(`πŸ“¦ MongoDB DB - ${MONGODB_DB}`);
 
558
  .catch((error) => {
559
  console.error('Failed to bootstrap application:', error);
560
  process.exit(1);
561
+ });