Advertisement
Guest User

Untitled

a guest
Nov 8th, 2018
123
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.04 KB | None | 0 0
  1. const Pool = require('pg').Pool
  2. const pool = new Pool({
  3. user: 'postgres',
  4. host: 'localhost',
  5. database: 'CarDB_1',
  6. password: 'phucduongoanh',
  7. port: 5432,
  8. })
  9.  
  10.  
  11.  
  12.  
  13. //////////////////////////////////////////////////
  14. const getCars = (request, response) => {
  15. pool.query('SELECT * FROM public.car ORDER BY id ASC', (error, results) => {
  16. if (error) {
  17. throw error
  18. }
  19. response.status(200).json(results.rows)
  20. })
  21. }
  22.  
  23.  
  24.  
  25. const getCarById = (request, response) => {
  26. const id = parseInt(request.params.id)
  27.  
  28. pool.query('SELECT * FROM public.car WHERE id = $1', [id], (error, results) => {
  29. if (error) {
  30. throw error
  31. }
  32. response.status(200).json(results.rows)
  33. })
  34. }
  35.  
  36.  
  37. const createCar = (request, response) => {
  38. const { brand, color, price, enginesize, quantity } = request.body
  39.  
  40. pool.query('INSERT INTO public.car (brand, color, price, enginesize, quantity) VALUES ($1, $2, $3, $4, $5)', [brand, color, price, enginesize, quantity], (error, results) => {
  41. if (error) {
  42. throw error
  43. }
  44. //response.status(201).send(`Car added with ID: ${result.insertId}`)
  45. response.status(201).send(`Car added`)
  46. })
  47. }
  48.  
  49. const updateCar = (request, response) => {
  50. const id = parseInt(request.params.id)
  51. const { brand, color, price, enginesize, quantity } = request.body
  52.  
  53. pool.query(
  54. 'UPDATE public.car SET brand = $1, color = $2, price = $3, enginesize = $4, quantity = $5 WHERE id = $6',
  55. [ brand, color, price, enginesize, quantity, id],
  56. (error, results) => {
  57. if (error) {
  58. throw error
  59. }
  60. response.status(200).send(`Car modified with ID: ${id}`)
  61. }
  62. )
  63. }
  64.  
  65. const deleteCar = (request, response) => {
  66. const id = parseInt(request.params.id)
  67.  
  68. pool.query('DELETE FROM public.car WHERE id = $1', [id], (error, results) => {
  69. if (error) {
  70. throw error
  71. }
  72. response.status(200).send(`Car deleted with ID: ${id}`)
  73. })
  74. }
  75.  
  76.  
  77. console.log(getCars)
  78.  
  79. module.exports = {
  80. getCars,
  81. getCarById,
  82. createCar,
  83. updateCar,
  84. deleteCar
  85. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement