-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.ts
More file actions
95 lines (82 loc) · 2.95 KB
/
server.ts
File metadata and controls
95 lines (82 loc) · 2.95 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
import express, { Request, Response, NextFunction } from 'express';
import bodyParser from 'body-parser';
import multer from 'multer';
import path from 'path';
import fs from 'fs';
import { handleDocumentProcessing } from './routes/documentRoutes';
import { handleQuizGeneration, handleQuizEvaluation } from './routes/quizRoutes';
const app = express();
const port = 3000;
// Middleware setup - only parse JSON for specific content types
app.use((req, res, next) => {
if (req.is('multipart/form-data')) {
next();
} else {
express.json()(req, res, next);
}
});
// File handling setup
const storage = multer.diskStorage({
destination: (_req, _file, cb) => cb(null, 'uploads/'),
filename: (_req, file, cb) => cb(null, `${Date.now()}_${file.originalname}`)
});
const upload = multer({ storage });
// CORS middleware
app.use(function (req: Request, res: Response, next: NextFunction) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
if (req.method === 'OPTIONS') {
res.sendStatus(200);
return;
}
next();
});
// Simple request logging
app.use((req: Request, _res: Response, next: NextFunction) => {
console.log(`[${new Date().toISOString()}] ${req.method} ${req.url}`);
if (req.body && !req.is('multipart/form-data')) {
console.log('Request body:', JSON.stringify(req.body, null, 2));
}
next();
});
// Simple response logging
app.use((req: Request, res: Response, next: NextFunction) => {
const originalJson = res.json;
res.json = function (body) {
console.log(`[${new Date().toISOString()}] Response ${res.statusCode} for ${req.url}`);
return originalJson.call(this, body);
};
next();
});
// Error handling
app.use((err: Error, _req: Request, res: Response, next: NextFunction) => {
console.error('Error:', err.message);
if (!res.headersSent) {
res.status(500).json({
status: 'error',
message: err.message
});
}
next(err);
});
// Async handler wrapper
const asyncHandler = (fn: (req: Request, res: Response, next: NextFunction) => Promise<any>) => (req: Request, res: Response, next: NextFunction) =>
Promise.resolve(fn(req, res, next)).catch(next);
// Initialize directories
['uploads', 'logs'].forEach((dir) => {
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir);
}
});
// Clean uploads folder
fs.readdirSync('uploads').forEach((file) => {
fs.unlinkSync(path.join('uploads', file));
});
// Routes
app.post('/api/chat-with-context', upload.array('files', 5), asyncHandler(handleDocumentProcessing));
app.post('/api/quiz/generate', asyncHandler(handleQuizGeneration));
app.post('/api/quiz/evaluate', asyncHandler(handleQuizEvaluation));
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});