-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
140 lines (122 loc) · 4.96 KB
/
Copy pathserver.js
File metadata and controls
140 lines (122 loc) · 4.96 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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
import express from 'express';
import cors from 'cors';
import path from 'path';
import { createServer as createViteServer } from 'vite';
import { CampusDatabase } from './src/db/db.js';
import dotenv from 'dotenv';
dotenv.config();
async function startServer() {
const app = express();
const PORT = process.env.PORT || 3000;
// Parse JSON bodies and enable CORS and urlencoded parsers
app.use(express.json());
app.use(cors());
app.use(express.urlencoded({ extended: true }));
// Connect to Database immediately when booting the server
await CampusDatabase.connect();
// API ROUTE: Get DB Status
app.get('/api/db-status', (req, res) => {
res.json({
status: 'online',
database: CampusDatabase.getModeString(),
mongoConnected: CampusDatabase.getModeString().includes('MongoDB')
});
});
// API ROUTE: Fetch all tickets with status group filtering support
app.get('/api/tickets', async (req, res) => {
try {
let tickets = await CampusDatabase.getTickets();
const { statusGroup } = req.query;
if (statusGroup === 'solved') {
tickets = tickets.filter(t => ['Completed', 'Resolved'].includes(t.status));
} else if (statusGroup === 'unsolved') {
tickets = tickets.filter(t => ['Pending', 'In Progress', 'Pending Review'].includes(t.status));
}
res.json(tickets);
} catch (error) {
console.error('API Error: GET /api/tickets', error);
res.status(500).json({ error: 'Failed to retrieve tickets' });
}
});
// API ROUTE: Create a new ticket
app.post('/api/tickets', async (req, res) => {
try {
const ticketData = req.body;
if (!ticketData.title || !ticketData.location || !ticketData.category) {
return res.status(400).json({ error: 'Missing required ticket fields' });
}
if (!ticketData.reporterId) {
return res.status(400).json({ error: 'Missing reporterId' });
}
// Generate ID if missing
if (!ticketData.id) {
const randomIDNum = Math.floor(1000 + Math.random() * 9000);
ticketData.id = `TK-${randomIDNum}`;
}
// Populate mandatory values if they aren't provided by client
ticketData.timeAgo = ticketData.timeAgo || 'Just now';
ticketData.createdTime = ticketData.createdTime || `Today, ${new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}`;
ticketData.status = ticketData.status || 'Pending';
ticketData.priority = ticketData.priority || 'High';
ticketData.assignedTo = ticketData.assignedTo || 'Unassigned';
ticketData.slaHours = ticketData.slaHours || 3;
ticketData.slaPercentRemaining = ticketData.slaPercentRemaining || 100;
ticketData.photos = ticketData.photos || [];
ticketData.history = ticketData.history || [];
const created = await CampusDatabase.createTicket(ticketData);
res.status(201).json(created);
} catch (error) {
console.error('API Error: POST /api/tickets', error);
res.status(500).json({ error: 'Failed to create new ticket' });
}
});
// API ROUTE: Update existing ticket status, comments, logs, or details
app.patch('/api/tickets/:id', async (req, res) => {
try {
const { id } = req.params;
const updates = req.body;
const updated = await CampusDatabase.updateTicket(id, updates);
if (!updated) {
return res.status(404).json({ error: `Ticket with ID ${id} not found.` });
}
res.json(updated);
} catch (error) {
console.error(`API Error: PATCH /api/tickets/${req.params.id}`, error);
res.status(500).json({ error: 'Failed to update ticket' });
}
});
// API ROUTE: Delete ticket
app.delete('/api/tickets/:id', async (req, res) => {
try {
const { id } = req.params;
const success = await CampusDatabase.deleteTicket(id);
if (!success) {
return res.status(404).json({ error: `Ticket with ID ${id} not found to delete.` });
}
res.json({ success: true, message: `Ticket ${id} successfully deleted from backend.` });
} catch (error) {
console.error(`API Error: DELETE /api/tickets/${req.params.id}`, error);
res.status(500).json({ error: 'Failed to delete ticket' });
}
});
// Integrate Vite Dev Server Middleware or Build output serving
if (process.env.NODE_ENV !== 'production') {
const vite = await createViteServer({
server: { middlewareMode: true },
appType: 'spa',
});
app.use(vite.middlewares);
console.log('Backend server running in DEVELOPMENT mode (Vite HMR/Middleware enabled)');
} else {
const distPath = path.join(process.cwd(), 'dist');
app.use(express.static(distPath));
app.get('*', (req, res) => {
res.sendFile(path.join(distPath, 'index.html'));
});
console.log('Backend server running in PRODUCTION mode (Serving static assets from dist/)');
}
app.listen(PORT, '0.0.0.0', () => {
console.log(`CampusFix Full-Stack services running on port http://localhost:${PORT}`);
});
}
startServer();