-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
117 lines (97 loc) · 2.51 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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
/*
This file was written by Tom Ngr.
It is released under the terms of What The Fuck Public Licence : do what the fuck you want with it.
*/
const express = require('express');
var fs = require('fs');
const app = express();
const port = 3000;
const userDataFile = './data/user.json'
const users = require(userDataFile);
const usersList = Object.values(users)[0];
const userChangeableProperties = [
"username",
"firstname",
"lastname",
"email",
"birth_date",
"gender",
"description",
// photo
"password"
]
function findUserById(id) {
for ( let i = 0 ; i < usersList.length ; i++) {
if (usersList[i].id == id) {
return usersList[i]
}
}
throw new Error ("User not found")
}
function sendUserNotFoundError(res) {
res.status = 404
res.send("User not found")
}
// simple root request to validate it works
app.get('/', (req, res) => {
res.send('Hello World!')
})
// GET all users data
app.get('/getAll', (req, res) => {
res.json({ users: usersList})
});
// GET one random user
app.get('/getOne', (req, res) => {
const randomUserIndex = Math.floor(Math.random() * usersList.length)
res.send(usersList[randomUserIndex])
});
app.get('/getById/:userId', (req, res) => {
const userId = req.params['userId']
console.log(userId)
try {
var user = findUserById(userId)
} catch {
sendUserNotFoundError(res)
}
res.send(user)
});
app.use(express.urlencoded({extended: true}))
app.post('/updateUser/:userId', (req, res) => {
const userId = req.params['userId']
try {
var user = findUserById(userId)
} catch {
sendUserNotFoundError(res)
}
updatedUser = updateUserProperties(user, req.body)
try { saveUsersData() }
catch {
res.status = 500
res.send("User was not updated")
}
res.json(updatedUser)
});
function updateUserProperties(user, properties) {
const propertiesList = Object.entries(properties);
propertiesList.map((keyValue) => {
userChangeableProperties.map(userChangeableProperty => {
if (keyValue[0] == userChangeableProperty) {
user[keyValue[0]] = keyValue[1]
}
})
})
return user
}
function saveUsersData() {
fs.writeFile(
userDataFile,
JSON.stringify({users: usersList}),
(err) => {
throw err
}
)
}
// make server listen
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
});