-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
55 lines (41 loc) · 1.22 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
const express = require('express');
const cors = require('cors');
const favicon = require('serve-favicon');
var path = require('path');
const app = express();
// CORS (Cross-Origin Resource Sharing) used when creating API with NodeJS
app.use(cors());
app.use(favicon(path.join(__dirname, 'redblazer-small.ico')));
const PORT = process.env.PORT || 8000;
const advices = require('./array').advices;
const data = [];
//add id for each objects
advices.forEach((item, i) => {
data.push(Object.assign({id: i, ...item}))
})
//function to get random object
function random(arr) {
const randomItem = Math.floor(Math.random() * arr.length);
const item = arr[randomItem];
return item;
}
//routing
app.get('/', (req, res) => {
res.json('Islamic advices API');
})
app.get('/advices', (req, res) => {
res.json(data);
})
app.get('/advice', (req, res) => {
res.json(random(data));
})
app.get('/advice/:id', (req, res) => {
const adviceId = parseInt(req.params.id);
const advice = data.find(item => item.id === adviceId);
if (advice) {
res.json(advice);
} else {
res.status(404).json({ error: 'Advice not found' });
}
})
app.listen(PORT, () => console.log(`PORT is running on ${PORT}`))