|
@@ -4,13 +4,41 @@ const express = require('express');
|
|
const app = express();
|
|
const app = express();
|
|
const bodyParser = require('body-parser');
|
|
const bodyParser = require('body-parser');
|
|
const ejs = require('ejs');
|
|
const ejs = require('ejs');
|
|
-const ph = require('pg');
|
|
|
|
|
|
+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 = {
|
|
const votes = {
|
|
sandwiches: 0,
|
|
sandwiches: 0,
|
|
tacos: 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 });
|
|
const urlencodedParser = bodyParser.urlencoded({ extended: false });
|
|
|
|
|
|
app.set('view engine', 'ejs');
|
|
app.set('view engine', 'ejs');
|
|
@@ -24,14 +52,30 @@ app.get('/', function (req, res) {
|
|
|
|
|
|
app.post('/vote', urlencodedParser, function (req, res) {
|
|
app.post('/vote', urlencodedParser, function (req, res) {
|
|
const vote = req.body.yourVote;
|
|
const vote = req.body.yourVote;
|
|
- if (vote == 'sandwiches') {
|
|
|
|
- votes.sandwiches++;
|
|
|
|
- }
|
|
|
|
- else if (vote == 'tacos') {
|
|
|
|
- votes.tacos++;
|
|
|
|
|
|
+
|
|
|
|
+ if (vote in votes) {
|
|
|
|
+ //language=PostgreSQL
|
|
|
|
+ const sql = `
|
|
|
|
+UPDATE votes
|
|
|
|
+SET number_of_votes = $1
|
|
|
|
+WHERE option_name = $2
|
|
|
|
+`;
|
|
|
|
+ const query = {
|
|
|
|
+ text: sql,
|
|
|
|
+ values: [votes[vote], vote]
|
|
|
|
+ };
|
|
|
|
+
|
|
|
|
+ votes[vote]++;
|
|
|
|
+ client.query(query, (err, res) => {
|
|
|
|
+ if (err) {
|
|
|
|
+ throw err;
|
|
|
|
+ }
|
|
|
|
+ console.log(`Rows modified for ${vote}: ${res.rowCount}.`);
|
|
|
|
+ });
|
|
}
|
|
}
|
|
else {
|
|
else {
|
|
console.log('Invalid vote:', vote);
|
|
console.log('Invalid vote:', vote);
|
|
|
|
+ // No query.
|
|
}
|
|
}
|
|
|
|
|
|
res.redirect('/');
|
|
res.redirect('/');
|