GymCo API
Frontend build not found. Run npm run build to serve the dashboard.
import express from 'express'; import cors from 'cors'; import helmet from 'helmet'; import rateLimit from 'express-rate-limit'; import fs from 'node:fs'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; import { env, isProduction } from './config/env.js'; import { prisma } from './config/prisma.js'; import { logger } from './config/logger.js'; import { requestId } from './common/middleware/requestId.js'; import { apiRouter } from './routes/index.js'; import { notFound } from './common/middleware/notFound.js'; import { errorHandler } from './common/middleware/errorHandler.js'; let redis = null; try { if (env.redisUrl) { const redisModule = await import('./config/redis.js'); redis = redisModule.redis; } } catch { // Redis not available, continue without cache } export const app = express(); const __dirname = path.dirname(fileURLToPath(import.meta.url)); const distPath = path.resolve(__dirname, '../dist'); const indexPath = path.join(distPath, 'index.html'); const uploadsPath = path.resolve(__dirname, '../uploads'); const hasFrontendBuild = fs.existsSync(indexPath); const { 'frame-ancestors': _frameAncestors, ...defaultCspDirectives } = helmet.contentSecurityPolicy.getDefaultDirectives(); app.set('trust proxy', 1); app.disable('x-powered-by'); app.use( helmet({ contentSecurityPolicy: { directives: { ...defaultCspDirectives, frameAncestors: ["'self'", 'https://huggingface.co', 'https://*.huggingface.co'], }, }, }) ); app.use( cors({ origin: env.corsOrigin === '*' ? true : env.corsOrigin.split(',').map((origin) => origin.trim()), credentials: true, }) ); const apiLimiter = rateLimit({ windowMs: env.rateLimitWindowMs, limit: env.rateLimitMax, standardHeaders: true, legacyHeaders: false, message: { success: false, message: 'Too many API requests. Please wait and try again.', }, skip: (req) => req.method === 'OPTIONS', }); app.use(express.json({ limit: '1mb' })); app.use(express.urlencoded({ extended: true })); app.use(requestId); app.use((req, res, next) => { const start = Date.now(); res.on('finish', () => { const duration = Date.now() - start; logger.info({ method: req.method, url: req.originalUrl, status: res.statusCode, duration, requestId: req.requestId, }, `${req.method} ${req.originalUrl} ${res.statusCode} ${duration}ms`); }); next(); }); app.use('/uploads', express.static(uploadsPath)); app.get('/health', async (_req, res) => { const start = Date.now(); let database = 'not_configured'; let poolMetrics = {}; if (env.databaseUrl) { try { await prisma.$queryRaw`SELECT 1`; database = 'ok'; const metrics = await prisma.$metrics.json(); poolMetrics = { poolConnections: metrics.gauges.find((g) => g.key === 'prisma_pool_connections_open')?.value, poolBusy: metrics.gauges.find((g) => g.key === 'prisma_pool_connections_busy')?.value, }; } catch { database = 'unreachable'; } } let redisStatus = 'not_configured'; if (redis) { try { const pong = await redis.ping(); redisStatus = pong === 'PONG' ? 'ok' : 'unreachable'; } catch { redisStatus = 'unreachable'; } } res.json({ success: true, status: 'ok', database, redis: redisStatus, uptime: process.uptime(), latencyMs: Date.now() - start, pool: poolMetrics, }); }); app.use('/api/v1', apiLimiter, apiRouter); if (hasFrontendBuild) { app.use(express.static(distPath, { index: false })); app.use((req, res, next) => { if (req.path.startsWith('/api/') || req.path === '/health') return next(); return res.sendFile(indexPath); }); } else { app.get('/', (_req, res) => { res.type('html').send(`
Frontend build not found. Run npm run build to serve the dashboard.