server.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. const express = require('express');
  2. const cors = require('cors');
  3. const path = require('path');
  4. const fs = require('fs');
  5. const uploadsDir = path.join(__dirname, '../uploads');
  6. if (!fs.existsSync(uploadsDir)) fs.mkdirSync(uploadsDir, { recursive: true });
  7. const app = express();
  8. app.use(cors());
  9. app.use(express.json());
  10. // Setup status endpoint (always available)
  11. app.use('/api/setup', require('./routes/setup'));
  12. // Middleware: block all other routes until DB is ready
  13. let dbReady = false;
  14. app.use((req, res, next) => {
  15. if (!dbReady) return res.status(503).json({ needsSetup: true });
  16. next();
  17. });
  18. // Routes
  19. app.use('/api/auth', require('./routes/auth'));
  20. app.use('/api/properties', require('./routes/properties'));
  21. app.use('/api/tenants', require('./routes/tenants'));
  22. app.use('/api/leases', require('./routes/leases'));
  23. app.use('/api/payments', require('./routes/payments'));
  24. app.use('/api/receipts', require('./routes/receipts'));
  25. app.use('/api/charges', require('./routes/charges'));
  26. app.get('/api/health', (_, res) => res.json({ ok: true }));
  27. async function start() {
  28. const { testConnection } = require('./db');
  29. const { createSchema } = require('./schema');
  30. const PORT = process.env.PORT || 3001;
  31. app.listen(PORT, () => console.log(`Server running on http://localhost:${PORT}`));
  32. // Wait for DB with retries
  33. let attempts = 0;
  34. while (attempts < 30) {
  35. const ok = await testConnection();
  36. if (ok) {
  37. try {
  38. await createSchema();
  39. dbReady = true;
  40. console.log('Database ready.');
  41. } catch (e) {
  42. console.error('Schema creation failed:', e.message);
  43. }
  44. break;
  45. }
  46. attempts++;
  47. console.log(`Waiting for database... (${attempts}/30)`);
  48. await new Promise(r => setTimeout(r, 2000));
  49. }
  50. if (!dbReady) console.error('Could not connect to database after 30 attempts.');
  51. }
  52. start();