-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathindex.js
60 lines (52 loc) · 1.74 KB
/
index.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
require('dotenv').config();
const express = require('express');
const mongoose = require('mongoose');
const app = express();
const cors = require('cors');
const port = process.env.API_PORT | 3000;
const mongoCollection = process.env.MONGO_COLLECTION;
const mongoUri = process.env.MONGO_URI;
const frontendUrl = `${process.env.FRONTEND_URL}`;
const starSchema = new mongoose.Schema({
proper: String,
con: String,
bay: String,
flam: Number,
mag: Number,
});
const Star = mongoose.model(mongoCollection, starSchema, mongoCollection);
console.log("connecting to " + mongoUri);
mongoose.connect(mongoUri)
.then(() => console.log('MongoDB connection successful'))
.catch(err => console.error('MongoDB connection error:', err));
const corsOptions = {
origin: frontendUrl,
};
app.use(cors(corsOptions));
app.use(express.json());
app.get('/constellation', async (req, res) => {
const { constellation } = req.query;
console.log(`calling /constellation for: ${constellation}`);
try {
const stars = await Star.find({
con: { $regex: constellation, $options: 'i' },
$or: [
{ bay: { $nin: [null, ''] } },
{ flam: { $nin: [null, ''] } },
{ proper: { $nin: [null, ''] } }
]
}).sort({ mag: 1 });
res.json(stars);
console.log(`Found stars: ${stars.length}`);
} catch (error) {
console.error('Error fetching star data:', error);
res.status(500).json({ message: 'internal server error' });
}
});
app.get('/', (req, res) => {
// console.log("calling root endpoint");
res.send('Welcome to the Starbugs API!');
});
app.listen(port, () => {
console.log(`API script is running on port ${port}.`);
});