forked from github/codespaces-react
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
66 lines (56 loc) · 1.68 KB
/
Copy pathserver.js
File metadata and controls
66 lines (56 loc) · 1.68 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
import express from 'express';
import cors from 'cors';
import dotenv from 'dotenv';
import { MongoClient } from 'mongodb';
dotenv.config();
const app = express();
const port = process.env.PORT || 4000;
const mongoUri = process.env.MONGO_URI || 'mongodb://127.0.0.1:27017';
const dbName = process.env.MONGO_DB || 'project_pm';
app.use(cors());
app.use(express.json());
let client;
let db;
async function connectToMongo() {
if (db) return db;
client = new MongoClient(mongoUri);
await client.connect();
db = client.db(dbName);
return db;
}
app.get('/health', (_req, res) => {
res.json({ status: 'ok' });
});
app.get('/history', async (_req, res) => {
try {
const database = await connectToMongo();
const history = await database.collection('project_history').find().sort({ archivedAt: -1 }).toArray();
res.json(history);
} catch (error) {
console.error(error);
res.status(500).json({ error: error.message });
}
});
app.post('/history', async (req, res) => {
try {
const database = await connectToMongo();
const result = await database.collection('project_history').insertOne(req.body);
res.json({ insertedId: result.insertedId });
} catch (error) {
console.error(error);
res.status(500).json({ error: error.message });
}
});
app.delete('/history', async (_req, res) => {
try {
const database = await connectToMongo();
const result = await database.collection('project_history').deleteMany({});
res.json({ deletedCount: result.deletedCount });
} catch (error) {
console.error(error);
res.status(500).json({ error: error.message });
}
});
app.listen(port, () => {
console.log(`PM backend listening on port ${port}`);
});