-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
88 lines (68 loc) · 1.6 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
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
const express = require('express')
const bodyParser = require('body-parser')
const app = express()
const port = 3000
const users = [
{
id: 1,
username: 'silvianaim',
password: 'Password123',
isFinished: true
},
{
id: 2,
username: 'naimsilvia',
password: '123Password',
isFinished: true
}
]
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
// read user
app.get('/user', (req, res) => {
res.json(users)
})
// read user
app.get('/user/:id', (req, res) => {
let result = null;
for (let i = 0; i < users.length; i++) {
if (users[i].id == req.params.id) {
result = users[i]
}
}
if (!result) {
res.sendStatus(404)
} else {
res.json(result)
}
})
// create user
app.post('/user', (req, res) => {
users.push(req.body)
res.json({ message: 'data created' })
})
// update user
app.patch('/user/:id', (req, res) => {
for (let i = 0; i < users.length; i++) {
if (users[i].id == req.params.id) {
users[i].isFinished = req.body.isFinished
}
}
res.json({ message: 'data updated' })
})
// delete user
app.delete('/user/:id', (req, res) => {
let index = null;
for (let i = 0; i < users.length; i++) {
if (users[i].id == req.params.id) {
index = [i]
}
}
users.splice(index, 1)
res.json({ message: 'data deleted' })
})
app.listen(port, () => {
console.log('Listening in port: ', port)
})