server.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. 'use strict';
  2. const express = require('express');
  3. const app = express();
  4. const bodyParser = require('body-parser');
  5. const ejs = require('ejs');
  6. const pg = require('pg');
  7. // Port number as seen from outside the PG container. Our run config maps the
  8. // internal 5432 to 9000 (beware machines with PHP-FPM on that port).
  9. // The IP is the "gateway" from "docker bridge"
  10. const client = new pg.Client('postgres://postgres@172.17.0.1:9000/postgres');
  11. const votes = {
  12. sandwiches: 0,
  13. tacos: 0,
  14. };
  15. client.connect((err, res) => {
  16. if (err) {
  17. throw err;
  18. }
  19. //language=PostgreSQL
  20. const sql = `
  21. SELECT option_name, number_of_votes
  22. FROM votes
  23. ORDER BY id
  24. `;
  25. client.query(sql, (err, res) => {
  26. if (err) {
  27. throw err;
  28. }
  29. for (const row of res.rows) {
  30. votes[row.option_name] = row.number_of_votes;
  31. }
  32. console.log(votes);
  33. });
  34. });
  35. const urlencodedParser = bodyParser.urlencoded({ extended: false });
  36. app.set('view engine', 'ejs');
  37. app.set('views', __dirname + '/views');
  38. app.get('/', function (req, res) {
  39. res.render('pages/index', {
  40. votes
  41. });
  42. });
  43. app.post('/vote', urlencodedParser, function (req, res) {
  44. const vote = req.body.yourVote;
  45. if (vote in votes) {
  46. //language=PostgreSQL
  47. const sql = `
  48. UPDATE votes
  49. SET number_of_votes = $1
  50. WHERE option_name = $2
  51. `;
  52. votes[vote]++;
  53. const query = {
  54. text: sql,
  55. values: [votes[vote], vote]
  56. };
  57. client.query(query, (err, res) => {
  58. if (err) {
  59. throw err;
  60. }
  61. console.log(`Rows modified for ${vote}: ${res.rowCount}.`);
  62. });
  63. }
  64. else {
  65. console.log('Invalid vote:', vote);
  66. // No query.
  67. }
  68. res.redirect('/');
  69. });
  70. const PORT = 8888;
  71. app.listen(PORT);
  72. console.log('Running on http://localhost:' + PORT);