Repository navigation
Expand file tree
/
Copy pathquotes-api.js
More file actions
54 lines (46 loc) · 1.45 KB
/
Copy pathquotes-api.js
File metadata and controls
54 lines (46 loc) · 1.45 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
// quotes-api.js
const express = require('express');
const fs = require('fs').promises;
const path = require('path');
const app = express();
app.use(express.json());
const FILE = path.join(__dirname, 'quotes.json');
async function readQuotes() {
try {
const d = await fs.readFile(FILE, 'utf8');
return JSON.parse(d);
} catch {
return [
{ id: '1', text: 'Start small, think big.', category: 'motivation' },
{ id: '2', text: 'Keep shipping.', category: 'career' }
];
}
}
async function writeQuotes(qs) {
await fs.writeFile(FILE, JSON.stringify(qs, null, 2));
}
app.get('/quotes', async (req, res) => {
const qs = await readQuotes();
res.json(qs);
});
app.get('/quotes/random', async (req, res) => {
const qs = await readQuotes();
const r = qs[Math.floor(Math.random() * qs.length)];
res.json(r);
});
app.get('/quotes/category/:cat', async (req, res) => {
const qs = await readQuotes();
res.json(qs.filter(q => q.category === req.params.cat));
});
app.post('/quotes', async (req, res) => {
const { text, category } = req.body;
if (!text) return res.status(400).json({ error: 'text required' });
const qs = await readQuotes();
const id = Date.now().toString();
const quote = { id, text, category: category || 'general' };
qs.push(quote);
await writeQuotes(qs);
res.status(201).json(quote);
});
const PORT = process.env.PORT || 4300;
app.listen(PORT, () => console.log(`Quotes API on http://localhost:${PORT}`));