| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162 |
- const express = require('express');
- const cors = require('cors');
- const path = require('path');
- const fs = require('fs');
- const uploadsDir = path.join(__dirname, '../uploads');
- if (!fs.existsSync(uploadsDir)) fs.mkdirSync(uploadsDir, { recursive: true });
- const app = express();
- app.use(cors());
- app.use(express.json());
- // Setup status endpoint (always available)
- app.use('/api/setup', require('./routes/setup'));
- // Middleware: block all other routes until DB is ready
- let dbReady = false;
- app.use((req, res, next) => {
- if (!dbReady) return res.status(503).json({ needsSetup: true });
- next();
- });
- // Routes
- app.use('/api/auth', require('./routes/auth'));
- app.use('/api/properties', require('./routes/properties'));
- app.use('/api/tenants', require('./routes/tenants'));
- app.use('/api/leases', require('./routes/leases'));
- app.use('/api/payments', require('./routes/payments'));
- app.use('/api/receipts', require('./routes/receipts'));
- app.use('/api/charges', require('./routes/charges'));
- app.get('/api/health', (_, res) => res.json({ ok: true }));
- async function start() {
- const { testConnection } = require('./db');
- const { createSchema } = require('./schema');
- const PORT = process.env.PORT || 3001;
- app.listen(PORT, () => console.log(`Server running on http://localhost:${PORT}`));
- // Wait for DB with retries
- let attempts = 0;
- while (attempts < 30) {
- const ok = await testConnection();
- if (ok) {
- try {
- await createSchema();
- dbReady = true;
- console.log('Database ready.');
- } catch (e) {
- console.error('Schema creation failed:', e.message);
- }
- break;
- }
- attempts++;
- console.log(`Waiting for database... (${attempts}/30)`);
- await new Promise(r => setTimeout(r, 2000));
- }
- if (!dbReady) console.error('Could not connect to database after 30 attempts.');
- }
- start();
|