-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
104 lines (86 loc) · 2.18 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
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
const express = require('express');
const bodyParser = require('body-parser');
const db = require('./db/db');
const NewsService = require('./service/news');
const Collector = require('./utils/collector');
//Set up express
const app = express();
//Parse incoming requests data
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.get('/api/v1/test', (req, res) => {
const news = new NewsService();
const collector = new Collector(news);
const data = collector.fetchData();
res.status(200).send({
success: 'true',
message: 'todos retrieved successfully',
todos: db
})
});
app.get('/api/v1/todos', (req, res) => {
res.status(200).send({
success: 'true',
message: 'todos retrieved successfully',
todos: db
})
});
app.post('/api/v1/todos', (req, res) => {
if (!req.body.title) {
return res.status(400).send({
success: 'false',
message: 'title is required'
});
} else if (!req.body.description) {
return res.status(400).send({
success: 'false',
message: 'description is required'
});
}
const todo = {
id: db.length + 1,
title: req.body.title,
description: req.body.description
};
db.push(todo);
return res.status(201).send({
success: 'true',
message: 'todo added successfully'
});
});
app.get('/api/v1/todos/:id', (req, res) => {
const id = parseInt(req.params.id, 10);
db.map((todo) => {
if (todo.id === id) {
return res.status(200).send({
success: 'true',
message: 'todo retrieved successfully',
todo,
});
}
});
return res.status(404).send({
success: 'false',
message: 'todo not found',
});
});
app.delete('/api/v1/todos/:id', (req, res) => {
const id = parseInt(req.params.id, 10);
db.map((todo, index) => {
if (todo.id === id) {
db.splice(index, 1);
return res.status(200).send({
success: 'true',
message: 'todo deleted successfully',
});
}
});
return res.status(404).send({
success: 'false',
message: 'todo not found',
});
});
const PORT = 5000;
app.listen(PORT, () => {
console.log(`server running on port ${PORT}`);
});