-
Notifications
You must be signed in to change notification settings - Fork 1
/
app.js
94 lines (86 loc) · 2.4 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
const express = require('express')
const fs = require('fs')
const cors = require('cors')
const app = express()
const port = 3033
app.use(cors())
app.use(express.json())
app.get('/api/tasks', (req, res) => {
fs.readFile('./data.json', 'utf-8', (err, data) => {
if(err) {
res.json(err)
} else {
const tasks = JSON.parse(data)
res.json(tasks)
}
})
})
app.post('/api/tasks', (req, res) => {
const body = req.body
body._id = Number(new Date())
fs.readFile('./data.json', 'utf-8', (err, data) => {
if(err) {
res.json(err)
} else {
const tasks = JSON.parse(data)
tasks.push(body)
fs.writeFile('./data.json', JSON.stringify(tasks), () => {
res.json(body)
})
}
})
})
app.get('/api/tasks/:id', (req, res) => {
const id = req.params.id
fs.readFile('./data.json', 'utf-8', (err, data) => {
if(err) {
res.json(err)
} else {
const tasks = JSON.parse(data)
const task = tasks.find(task => task.id == id)
if(task) {
res.json(task)
} else {
res.json({})
}
}
})
})
app.put('/api/tasks/:id', (req, res) => {
const id = req.params.id
const body = req.body
fs.readFile('./data.json', 'utf-8', (err, data) => {
if(err) {
res.json(err)
} else {
const tasks = JSON.parse(data)
const task = tasks.find(task => task.id == id)
if(task) {
Object.assign(task, body)
fs.writeFile('./data.json', JSON.stringify(tasks), () => {
res.json(task)
})
} else {
res.json({})
}
}
})
})
app.delete('/api/tasks/:id', (req, res) => {
const id = req.params.id
fs.readFile('./data.json', 'utf-8', (err, data) => {
if(err) {
res.json(err)
} else {
let tasks = JSON.parse(data)
const task = tasks.find(task => task.id == id)
tasks = tasks.filter(task => task.id != id)
fs.writeFile('./data.json', JSON.stringify(tasks), () => {
res.json(task)
})
}
})
})
app.listen(port, () => {
console.log('listening on port', port)
})