-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
69 lines (55 loc) · 1.65 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
61
62
63
64
65
66
67
68
import express from "express";
import axios from "axios";
import dotenv from "dotenv";
dotenv.config();
const app = express();
const port = 3000;
const API_URL = "https://api.nasa.gov/planetary/apod"
app.use(express.static("public"));
const myAPIKey = process.env.API_KEY;
// Function to fetch APoD data
async function fetchApodData(apiKey, date = null) {
const params = { api_key: apiKey };
if (date) {
params.date = date;
}
try {
const response = await axios.get(API_URL, { params });
return response.data;
} catch (error) {
throw error;
}
}
// Route to fetch the APoD data (home page)
app.get("/", async (req, res) => {
try {
const apodData = await fetchApodData(myAPIKey);
res.render("apod.ejs", { apodData });
} catch (error) {
console.error(error);
res.status(500).send('Error fetching APoD data');
}
});
// Route to search for APoD data by date
app.get("/search", async (req, res) => {
const requestedDate = req.query.searchByDate;
console.log(requestedDate);
// Earliest available date
const earliestDate = new Date("1995-01-01");
const requested = new Date(requestedDate);
const currentDate = new Date();
// Check if the requested date is earlier than the earliest available date
if (requested < earliestDate || requested > currentDate) {
return res.status(400).render("error.ejs");
}
try {
const apodData = await fetchApodData(myAPIKey, requestedDate);
res.render("apod.ejs", { apodData });
} catch (error) {
console.error(error);
res.status(500).send('Error fetching APoD data');
}
});
app.listen(port, () => {
console.log(`Server is running on port ${port}.`);
});