-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
60 lines (53 loc) · 1.61 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
const express = require('express');
const cors = require('cors'); // Import the cors package
const app = express();
const countries = require('./countries.json');
// Middleware to parse JSON request bodies
app.use(express.json());
// Use the cors middleware
app.use(cors());
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
// Route to get all countries or filtered by continent, random count, or specific country
app.get('/data', (req, res) => {
const { continent, random, country } = req.query;
let filteredCountries = [...countries];
// Filter by continent
if (continent) {
filteredCountries = filteredCountries.filter(
(c) => c.continent.toLowerCase() === continent.toLowerCase()
);
}
// Get random countries
if (random) {
const count = parseInt(random);
if (isNaN(count) || count < 1) {
return res.status(400).json({ error: 'Invalid random parameter' });
}
filteredCountries = filteredCountries
.sort(() => Math.random() - 0.5)
.slice(0, count);
}
// Get a specific country
if (country) {
const countryData = filteredCountries.find(
(c) => c.name.toLowerCase() === country.toLowerCase()
);
if (countryData) {
return res.json(countryData);
} else {
return res.status(404).json({ error: 'Country not found' });
}
}
if (filteredCountries.length > 0) {
res.json(filteredCountries);
} else {
res.status(404).json({ error: 'No countries found' });
}
});
// Start the server
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});