|
| 1 | +import express, { Express } from 'express'; |
| 2 | +import path from 'path'; |
| 3 | +import { fileURLToPath } from 'url'; |
| 4 | +import { existsSync } from 'fs'; |
| 5 | +import cors from 'cors'; |
| 6 | +import cookieParser from 'cookie-parser'; |
| 7 | +import authRoutes from './routes/auth.js'; |
| 8 | +import jamsRoutes from './routes/jams.js'; |
| 9 | + |
| 10 | +const __dirname = path.dirname(fileURLToPath(import.meta.url)); |
| 11 | + |
| 12 | +export function createApiServer(): Express { |
| 13 | + const app = express(); |
| 14 | + |
| 15 | + // Middleware |
| 16 | + app.use( |
| 17 | + cors({ |
| 18 | + origin: process.env.CORS_ORIGIN || 'http://localhost:5173', |
| 19 | + credentials: true, |
| 20 | + }) |
| 21 | + ); |
| 22 | + app.use(express.json()); |
| 23 | + app.use(cookieParser()); |
| 24 | + |
| 25 | + // Health check |
| 26 | + app.get('/api/health', (_req, res) => { |
| 27 | + res.json({ status: 'ok' }); |
| 28 | + }); |
| 29 | + |
| 30 | + // API routes |
| 31 | + app.use('/api/auth', authRoutes); |
| 32 | + app.use('/api/jams', jamsRoutes); |
| 33 | + |
| 34 | + // Serve React SPA static files in production |
| 35 | + const clientDist = path.resolve(__dirname, '../../../client/dist'); |
| 36 | + if (existsSync(clientDist)) { |
| 37 | + app.use(express.static(clientDist)); |
| 38 | + |
| 39 | + // SPA catch-all: serve index.html for non-API routes |
| 40 | + app.get('/{*splat}', (_req, res) => { |
| 41 | + res.sendFile(path.join(clientDist, 'index.html')); |
| 42 | + }); |
| 43 | + |
| 44 | + console.log(`Serving client from ${clientDist}`); |
| 45 | + } |
| 46 | + |
| 47 | + return app; |
| 48 | +} |
| 49 | + |
| 50 | +export function startApiServer(): Express { |
| 51 | + const app = createApiServer(); |
| 52 | + const port = process.env.PORT || process.env.HTTP_PORT || 3000; |
| 53 | + |
| 54 | + app.listen(port, () => { |
| 55 | + console.log(`API server listening on port ${port}`); |
| 56 | + }); |
| 57 | + |
| 58 | + return app; |
| 59 | +} |
0 commit comments