-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathusers.js
91 lines (83 loc) · 1.78 KB
/
users.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
const createError = require("http-errors");
const { User } = require("../db/models");
const { successResponse } = require("../utils/response");
/**
* Retrieve all users from DB.
*/
const getAll = (req, res, next) => {
User.findAll({
attributes: {
exclude: ["password"],
},
})
.then((users) => {
res.status(200).json(successResponse(users));
})
.catch(next);
};
/**
* Create a new user.
*/
const createUser = (req, res, next) => {
User.create(req.body, {
fields: ["firstName", "lastName", "email", "password"],
})
.then((user) => {
res.status(201).json(successResponse(User.sanitize(user)));
})
.catch(next);
};
/**
* Retrieve a user by Id.
*/
const getUserById = (req, res, next) => {
User.findByPk(req.params.id, {
attributes: {
exclude: ["password"],
},
})
.then((user) => {
if (!user) {
throw createError(404, "User not found.");
}
res.status(200).json(successResponse(User.sanitize(user)));
})
.catch(next);
};
/**
* Update a user by Id.
*/
const updateUserById = (req, res, next) => {
User.findByPk(req.params.id)
.then((user) => {
if (!user) {
throw createError(404, "User not found.");
}
return user.update(req.body, {
fields: ["firstName", "lastName", "password"],
});
})
.then((user) => {
res.status(200).json(successResponse(User.sanitize(user)));
})
.catch(next);
};
/**
* Delete a user from DB.
*/
const deleteUserById = (req, res, next) => {
User.destroy({
where: { id: req.params.id },
})
.then((result) => {
res.status(200).json(successResponse({ result }));
})
.catch(next);
};
module.exports = {
getAll,
createUser,
getUserById,
updateUserById,
deleteUserById,
};