-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
80 lines (67 loc) · 2.46 KB
/
server.js
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
const express = require('express');
const { MongoClient } = require('mongodb');
const cors = require('cors');
const path = require('path');
const app = express();
app.use(express.json());
app.use(cors({ credentials: true, origin: 'http://54.180.120.249:80' }));
const uri = 'mongodb+srv://sparta:[email protected]/?retryWrites=true&w=majority';
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
let db, articleCollection, rankCollection, transferCollection;
async function connectToMongoDB() {
try {
await client.connect();
console.log('Connected to MongoDB');
db = client.db('kickoff');
articleCollection = db.collection('article');
rankCollection = db.collection('rank');
transferCollection = db.collection('transfer');
} catch (error) {
console.error('Error connecting to MongoDB:', error);
}
}
connectToMongoDB();
app.get('/article', async (req, res) => {
const pageNumber = req.query.pageNumber ? parseInt(req.query.pageNumber) : 1;
const PAGE_SIZE = 3;
try {
const articles = await articleCollection
.find({})
.sort({ _id: -1 }) // _id를 기준으로 역순으로 정렬
.skip((pageNumber - 1) * PAGE_SIZE)
.limit(PAGE_SIZE)
.toArray();
res.json({ result: 'success', article: articles });
} catch (error) {
console.error('Error fetching articles:', error);
res.status(500).json({ result: 'error', message: 'Internal server error' });
}
});
app.get('/rank', async (req, res) => {
try {
const ranks = await rankCollection.find({}).toArray();
res.json({ result: 'success', rank: ranks });
} catch (error) {
console.error('Error fetching ranks:', error);
res.status(500).json({ result: 'error', message: 'Internal server error' });
}
});
app.get('/transfer', async (req, res) => {
try {
const transfers = await transferCollection.find({}).toArray();
res.json({ result: 'success', transfer: transfers });
} catch (error) {
console.error('Error fetching transfers:', error);
res.status(500).json({ result: 'error', message: 'Internal server error' });
}
});
// Serve static files from the React app
app.use(express.static(path.join(__dirname, 'dist')));
// Catch all other routes and return the React app
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'dist', 'index.html'));
});
const PORT = process.env.PORT || 80;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});