kaboot/server/src/index.ts

51 lines
1.4 KiB
TypeScript

import express, { Request, Response, NextFunction } from 'express';
import cors from 'cors';
import { db } from './db/connection.js';
import quizzesRouter from './routes/quizzes.js';
import usersRouter from './routes/users.js';
const app = express();
const PORT = process.env.PORT || 3001;
app.use(cors({
origin: process.env.CORS_ORIGIN || 'http://localhost:5173',
credentials: true,
}));
app.use((req: Request, res: Response, next: NextFunction) => {
express.json({ limit: '10mb' })(req, res, (err) => {
if (err instanceof SyntaxError && 'body' in err) {
res.status(400).json({ error: 'Invalid JSON' });
return;
}
if (err) {
next(err);
return;
}
next();
});
});
app.get('/health', (_req: Request, res: Response) => {
res.json({ status: 'ok', timestamp: new Date().toISOString() });
});
app.use('/api/quizzes', quizzesRouter);
app.use('/api/users', usersRouter);
app.use((err: Error, _req: Request, res: Response, _next: NextFunction) => {
console.error('Unhandled error:', err);
res.status(500).json({ error: 'Internal server error' });
});
app.listen(PORT, () => {
console.log(`Kaboot backend running on port ${PORT}`);
console.log(`Database: ${process.env.DATABASE_PATH || 'default location'}`);
console.log(`CORS origin: ${process.env.CORS_ORIGIN || 'http://localhost:5173'}`);
});
process.on('SIGTERM', () => {
console.log('Shutting down...');
db.close();
process.exit(0);
});