-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathqueries.js
More file actions
108 lines (87 loc) · 2.39 KB
/
Copy pathqueries.js
File metadata and controls
108 lines (87 loc) · 2.39 KB
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
const Pool = require('pg').Pool
const pool = new Pool({
user: 'postgres',
host: 'localhost',
database: 'postgres',
password: 'Keyin2021',
port: 5432,
})
const getUsers = (request, response) => {
const id = parseInt(request.query.name)
pool.query('SELECT * FROM test_20220908.users ORDER BY id ASC', (error, results) => {
if (error) {
throw error
}
response.status(200).json(results.rows)
})
}
const getUserById = (request, response) => {
const id = parseInt(request.params.id)
console.log("Id = " + id)
pool.query('SELECT * FROM test_20220908.users WHERE id = $1', [id], (error, results) => {
if (error) {
throw error
}
response.status(200).json(results.rows)
})
}
const findUsersBySearch = (request, response) => {
const id = parseInt(request.query.id)
const name = request.query.name
var sqlStmt = 'SELECT * FROM test_20220908.users where '
if (!name == false) {
sqlStmt += ("name = '" + name + "' ")
console.log("adding name = " + name)
}
if (!Number.isNaN(id)) {
sqlStmt += ("AND id = " + id)
console.log("Id = " + id)
}
console.log(sqlStmt)
pool.query(sqlStmt, (error, results) => {
if (error) {
throw error
}
response.status(200).json(results.rows)
})
}
const createUser = (request, response) => {
const { id, name, course_id } = request.body
pool.query('INSERT INTO test_20220908.users (id, name, course_id) VALUES ($1, $2, $3)', [id, name, course_id], (error, results) => {
if (error) {
throw error
}
response.status(201).send(`User added with ID: ${results.insertId}`)
})
}
const updateUser = (request, response) => {
const id = parseInt(request.params.id)
const { name, course_id } = request.body
pool.query(
'UPDATE test_20220908.users SET name = $1, course_id = $2 WHERE id = $3',
[name, course_id, 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 test_20220908.users WHERE id = $1', [id], (error, results) => {
if (error) {
throw error
}
response.status(200).send(`User deleted with ID: ${id}`)
})
}
module.exports = {
getUsers,
getUserById,
findUsersBySearch,
createUser,
updateUser,
deleteUser,
}