Skip to content

Instantly share code, notes, and snippets.

@kwhinnery
Created Oct 25, 2019
Embed
What would you like to do?
const pool = require('./config');
require('dotenv').config()
const getUsers = (request, response) => {
pool.connect().then(client => {
client.query('SELECT * FROM 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)
pool.query('SELECT * FROM users WHERE id = $1', [id], (error, results) => {
if (error) {
throw error
}
response.status(200).json(results.rows)
})
}
const createUser = (request, response) => {
const { last_name, first_name, email, account_type } = request.body
pool.query('INSERT INTO users (last_name, first_name, email, account_type) VALUES ($1, $2, $3, $4)', [last_name, first_name, email, account_type], (error, results) => {
if (error) {
throw error
}
response.status(201).send(`User added with ID: ${result.insertId}`)
})
}
const updateUser = (request, response) => {
const id = parseInt(request.params.id)
const { last_name, first_name, email, account_type } = request.body
pool.query(
'UPDATE users SET last_name = $1, first_name = $2, email = $3, account_type = $4 WHERE id = $5',
[last_name, first_name, email, account_type, 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)
const { last_name, first_name, email, account_type } = request.body
pool.query(
'DELETE FROM users WHERE id = $1', [id], (error, results) => {
if (error) {
throw error
}
response.status(200).send(`User deleted with ID: ${id}`)
})
}
module.exports = {
getUsers,
getUserById,
createUser,
updateUser,
deleteUser,
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment