'use strict'; const express = require('express'); const app = express(); const bodyParser = require('body-parser'); const ejs = require('ejs'); const pg = require('pg'); // Port number as seen from outside the PG container. Our run config maps the // internal 5432 to 9000 (beware machines with PHP-FPM on that port). // The IP is the "gateway" from "docker bridge" const client = new pg.Client('postgres://postgres@172.17.0.1:9000/postgres'); const votes = { sandwiches: 0, tacos: 0, }; client.connect((err, res) => { if (err) { throw err; } //language=PostgreSQL const sql = ` SELECT option_name, number_of_votes FROM votes ORDER BY id `; client.query(sql, (err, res) => { if (err) { throw err; } for (const row of res.rows) { votes[row.option_name] = row.number_of_votes; } console.log(votes); }); }); const urlencodedParser = bodyParser.urlencoded({ extended: false }); app.set('view engine', 'ejs'); app.set('views', __dirname + '/views'); app.get('/', function (req, res) { res.render('pages/index', { votes }); }); app.post('/vote', urlencodedParser, function (req, res) { const vote = req.body.yourVote; if (vote in votes) { //language=PostgreSQL const sql = ` UPDATE votes SET number_of_votes = $1 WHERE option_name = $2 `; votes[vote]++; const query = { text: sql, values: [votes[vote], vote] }; client.query(query, (err, res) => { if (err) { throw err; } console.log(`Rows modified for ${vote}: ${res.rowCount}.`); }); } else { console.log('Invalid vote:', vote); // No query. } res.redirect('/'); }); const PORT = 8888; app.listen(PORT); console.log('Running on http://localhost:' + PORT);