Repository navigation
Expand file tree
/
Copy pathindex.js
More file actions
84 lines (73 loc) · 2.01 KB
/
Copy pathindex.js
File metadata and controls
84 lines (73 loc) · 2.01 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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
const PORT = 8000;
import express from "express";
import axios from "axios";
import cheerio from "cheerio";
import { sites } from "./sites.js";
import cors from "cors";
const app = express();
app.use(cors());
let facts = [];
let id = 0;
sites.forEach((site) => {
//let id = 0;
axios
.get(site.address)
.then((response) => {
const html = response.data;
const $ = cheerio.load(html);
$("li:not(:has(>a))", html).each(function () {
const fact = $(this).text().trim();
const trimmedFact = fact
.replace(/(?:[\.\?!]\s*\d+\b|”\s*\d+\b)/g, "")
.trim();
if (
trimmedFact !== " " &&
trimmedFact !== "Close this sub-navigation"
) {
facts.push({ id, fact: trimmedFact });
id++;
}
});
})
.catch((error) => {
console.log(error);
});
});
app.get("/", (req, res) => {
res.json("Welcome to the Interesting Climate Facts API");
});
//* get random facts
app.get("/random", (req, res) => {
const randomIndex = Math.floor(Math.random() * facts.length);
const randomFact = facts[randomIndex].fact;
res.json(randomFact);
});
//* get a list of all the facts
app.get("/facts", (req, res) => {
res.json(facts);
});
//* get a fact by ID
app.get("/fact/:id", async (req, res) => {
const factId = req.params.id;
const getById = facts.filter((fact) => fact.id == factId)[0]?.fact;
if (getById) {
res.json(getById);
} else {
res.status(404).json({ error: `Fact with ID ${factId} not found` });
}
});
//* get facts by keyword
app.get("/search/:term", (req, res) => {
const searchTerm = req.params.term.toLowerCase();
const searchResults = facts.filter((fact) => {
if (fact.fact) {
return fact.fact.toLowerCase().includes(searchTerm);
} else {
res.status(404).json({ error: `Fact with term ${searchTerm} not found` });
}
});
res.json(searchResults);
});
app.listen(PORT, () => console.log(`server running on port ${PORT}`));
// index.js
//export default app;