|
| 1 | +// Copyright 2020 Google LLC |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | + |
| 15 | +'use strict'; |
| 16 | + |
| 17 | +const { getVotes, getVoteCount, insertVote } = require('./cloud-sql'); |
| 18 | +const express = require('express'); |
| 19 | +const { buildRenderedHtml } = require('./handlebars'); |
| 20 | +const { authenticateJWT, requestLogger } = require('./middleware'); |
| 21 | + |
| 22 | +const app = express(); |
| 23 | +app.use(express.static(__dirname + '/static')); |
| 24 | + |
| 25 | +// Automatically parse request body as form data. |
| 26 | +app.use(express.urlencoded({extended: false})); |
| 27 | +app.use(express.json()); |
| 28 | + |
| 29 | +// Set Content-Type for all responses for these routes. |
| 30 | +app.use((req, res, next) => { |
| 31 | + res.set('Content-Type', 'text/html'); |
| 32 | + next(); |
| 33 | +}); |
| 34 | + |
| 35 | +app.get('/', requestLogger, async (req, res) => { |
| 36 | + try { |
| 37 | + // Query the total count of "CATS" from the database. |
| 38 | + const catsResult = await getVoteCount('CATS'); |
| 39 | + const catsTotalVotes = parseInt(catsResult[0].count); |
| 40 | + // Query the total count of "DOGS" from the database. |
| 41 | + const dogsResult = await getVoteCount('DOGS'); |
| 42 | + const dogsTotalVotes = parseInt(dogsResult[0].count); |
| 43 | + // Query the last 5 votes from the database. |
| 44 | + const votes = await getVotes(); |
| 45 | + // Calculate and set leader values. |
| 46 | + let leadTeam = ''; |
| 47 | + let voteDiff = 0; |
| 48 | + let leaderMessage = ''; |
| 49 | + if (catsTotalVotes !== dogsTotalVotes) { |
| 50 | + if (catsTotalVotes > dogsTotalVotes) { |
| 51 | + leadTeam = 'CATS'; |
| 52 | + voteDiff = catsTotalVotes - dogsTotalVotes; |
| 53 | + } else { |
| 54 | + leadTeam = 'DOGS'; |
| 55 | + voteDiff = dogsTotalVotes - catsTotalVotes; |
| 56 | + } |
| 57 | + leaderMessage = `${leadTeam} are winning by ${voteDiff} vote${voteDiff > 1 ? 's' : ''}.`; |
| 58 | + } else { |
| 59 | + leaderMessage = 'CATS and DOGS are evenly matched!'; |
| 60 | + } |
| 61 | + |
| 62 | + // Add variables to Handlebars.js template |
| 63 | + const renderedHtml = await buildRenderedHtml({ |
| 64 | + votes: votes, |
| 65 | + catsCount: catsTotalVotes, |
| 66 | + dogsCount: dogsTotalVotes, |
| 67 | + leadTeam: leadTeam, |
| 68 | + voteDiff: voteDiff, |
| 69 | + leaderMessage: leaderMessage, |
| 70 | + }); |
| 71 | + res.status(200).send(renderedHtml); |
| 72 | + } catch (err) { |
| 73 | + const message = "Error while connecting to the Cloud SQL database. " + |
| 74 | + "Check that your username and password are correct, that the Cloud SQL " + |
| 75 | + "proxy is running (locally), and that the database/table exists and is " + |
| 76 | + `ready for use: ${err}`; |
| 77 | + req.logger.error(message); // request-based logger with trace support |
| 78 | + res |
| 79 | + .status(500) |
| 80 | + .send('Unable to load page; see logs for more details.') |
| 81 | + .end(); |
| 82 | + } |
| 83 | +}); |
| 84 | + |
| 85 | +app.post('/', requestLogger, authenticateJWT, async (req, res) => { |
| 86 | + // Get decoded Id Platform user id |
| 87 | + const uid = req.uid; |
| 88 | + // Get the team from the request and record the time of the vote. |
| 89 | + const {team} = req.body; |
| 90 | + const timestamp = new Date(); |
| 91 | + |
| 92 | + if (!team || (team !== 'CATS' && team !== 'DOGS')) { |
| 93 | + res.status(400).send('Invalid team specified.').end(); |
| 94 | + return; |
| 95 | + } |
| 96 | + |
| 97 | + // Create a vote record to be stored in the database. |
| 98 | + const vote = { |
| 99 | + candidate: team, |
| 100 | + time_cast: timestamp, |
| 101 | + uid, |
| 102 | + }; |
| 103 | + |
| 104 | + // Save the data to the database. |
| 105 | + try { |
| 106 | + await insertVote(vote); |
| 107 | + req.logger.info({message: 'vote_inserted', vote}); // request-based logger with trace support |
| 108 | + } catch (err) { |
| 109 | + req.logger.error(`Error while attempting to submit vote: ${err}`); |
| 110 | + res |
| 111 | + .status(500) |
| 112 | + .send('Unable to cast vote; see logs for more details.') |
| 113 | + .end(); |
| 114 | + return; |
| 115 | + } |
| 116 | + res.status(200).send(`Successfully voted for ${team} at ${timestamp}`).end(); |
| 117 | +}); |
| 118 | + |
| 119 | +module.exports = app; |
0 commit comments