-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathqueries.js
93 lines (71 loc) · 2.41 KB
/
queries.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
const Pool = require('pg').Pool;
const pool = new Pool({
user: 'root',
host: 'localhost',
database: 'codinglone',
password: 'fab3227423',
port: 5432,
})
const bcrypt = require('bcrypt');
const getUsers = (request, response) => {
pool.query('SELECT * FROM users ORDER BY email ASC', (error, results) => {
if(error){
throw error
}
response.status(200).json(results.rows)
})
}
const getUserById = (request, response) => {
const id = parseInt(request.params.id);
pool.query('SELECT * FROM users WHERE id = $1', [id], (error, results) => {
if(error){
throw error;
}
response.status(200).json(results.rows)
})
}
const createUser = async(request, response) => {
const { password, email } = request.body;
const hashedPassword = await bcrypt.hash(password, 10);
pool.query('INSERT INTO users (email, password) VALUES ($1, $2) RETURNING *', [email, hashedPassword], (error, results) => {
if(error){
throw error;
}
response.status(201).send(`User added with ID: ${results.rows[0].id}`)
})
}
const updateUser = async(request, response) => {
const id = parseInt(request.params.id);
const { email, password } = request.body;
const hashedPassword = await bcrypt.hash(password, 10);
pool.query('UPDATE users SET email=$1, password=$2 WHERE id = $3', [email, hashedPassword, id], (error, results) => {
if(error){
throw error;
}
response.status(200).send(`User modified with ID: ${id}`)
})
}
const deleteUser = (request, response) => {
const id = parseInt(request.params.id)
pool.query('DELETE FROM users WHERE id = $1', [id], (error, results) => {
if(error){
throw error;
}
response.status(200).send(`User deleted with ID: ${id}`)
})
}
const handleLogin = async(request, response) => {
const { email, password } = request.body;
if( !email || !password ) return response.status(400).json({ 'message': 'Username and password are required' });
const foundUser = pool.query(`SELECT * FROM users WHERE email=${email}`);
if(!foundUser) return response.status(401); //unauthorized
// evaluate password
const match = await bcrypt.compare(password, foundUser.password);
}
module.exports = {
getUsers,
getUserById,
createUser,
updateUser,
deleteUser
}