-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.js
50 lines (41 loc) · 1.17 KB
/
app.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
const express = require("express");
const fs = require("fs");
const path = require("path");
const cors = require("cors");
const app = express();
app.use(cors());
const PORT = process.env.PORT || 3001;
const quotesFilePath = path.join(__dirname, "quotes.json");
// Function to read quotes from the JSON file
const getQuotes = () => {
const data = fs.readFileSync(quotesFilePath);
return JSON.parse(data);
};
// Endpoint to check ping
app.get("/ping", (req, res) => {
res.send('pong');
});
// Endpoint to get all quotes
app.get("/v1/quotes", (req, res) => {
const quotes = getQuotes();
res.json(quotes);
});
// Endpoint to get a random quote
app.get("/v1/quotes/random", (req, res) => {
const quotes = getQuotes();
const randomIndex = Math.floor(Math.random() * quotes.length);
res.json(quotes[randomIndex]);
});
// Endpoint to get a quote by ID
app.get("/v1/quotes/:id", (req, res) => {
const quotes = getQuotes();
const quote = quotes.find((q) => q.id === parseInt(req.params.id));
if (quote) {
res.json(quote);
} else {
res.status(404).json({ error: "Quote not found" });
}
});
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});