Build a social poll app with counter using Node.js
This tutorial assumes you have Node.js, MongoDB and Express installed.
Over the years, web apps have come a long way, incorporating various technologies and techniques to create a more engaging experience for the user. Realtime technologies are one such improvement. They provide a powerful means of transforming an app into a social activity.
In this article, we’ll build a polls app. The home page of our app will display a list of polls. A visitor can vote on as many polls as they wish from the home page. Each time a new vote is cast on any poll, the number of votes for the different choices in that poll will update in realtime. Here’s a demo of the app:
You can check out the source code of the completed application on GitHub.
Set up the project
This tutorial assumes you have Node.js and MongoDB installed. We’ll be using Express, a popular lightweight Node.js framework. Let’s get started by using the express application generator:
If you don’t already have it installed:
npm install express-generator -g
Create a new express app with view engine set to Handlebars (hbs)
express --view=hbs pollser
cd pollser && npm install
Then we’ll add our dependencies:
npm install --save dotenv mongoose pusher
Here’s a breakdown of what each module is for:
- We’re using MongoDB for our data store, so we’ll use Mongoose to map our models (JavaScript objects) to MongoDB documents.
- We need Pusher to talk to Pusher’s APIs.
- Lastly, dotenv is a small package that helps us load our private configuration variables (namely our Pusher app credentials) from a .env file.
We’ll store our polls in a polls collection. Here’s an example of what a single item in this collection will look like:
{
"topic": "Should dogs be allowed to fly?"
"choices": [
{
"value": "Yes",
"votes": 2,
"id": 0
},
{
"value": "No",
"votes": 7,
"id": 1
},
{
"value": "Perhaps",
"votes": 17,
"id": 2
}
]
}
Let’s define our Poll model. We’ll put this in models/poll.js
:
let mongoose = require('mongoose');
let Poll = mongoose.model('Poll', {
topic: String,
choices: [
{
value: String,
votes: Number
}
]
});
module.exports = Poll;
Next up, let’s populate our database with some fake polls. Create a file called seed.js
in the bin directory, with the following content:
require('mongoose').connect('mongodb://localhost/pollser');
const topics = [
"Should dogs be allowed to fly?",
"Should doors be shut at night?",
"Should developers use IDEs?",
"Should cars have four wheels?",
"Should humans be allowed to wear shoes?"
];
let Poll = require('../models/poll');
// empty the collection first
Poll.remove({})
.then(() => {
let polls = [];
for (let i = 0; i < 5; i++) {
polls.push({
topic: topics[i],
choices: [
{
value: "Yes",
votes: Math.round(Math.random() * 20)
},
{
value: "No",
votes: Math.round(Math.random() * 20)
},
{
value: "I really don't care",
votes: Math.round(Math.random() * 20)u
}
]
});
}
return Poll.create(polls);
})
.then(() => {
process.exit();
})
.catch((e) => {
console.log(e);
process.exit(1);
});
Run the seed using node (remember to start your MongoDB server by running mongod
first):
node bin/seed.js
Retrieving and rendering polls
Let’s add our MongoDB connection setup to our app.js file, so the connection gets created when our app starts.
// below this line:
var app = express();
// add this
require('mongoose').connect('mongodb://localhost/pollser');
Next up is our route. Here, we’ll retrieve all polls from the database and pass them to the view. Replace the code in routes/index.js with this:
let router = require('express').Router();
let Poll = require('./../models/poll');
router.get('/', (req, res, next) => {
Poll.find().exec((err, polls) => {
res.render('index', { polls: polls });
});
});
module.exports = router;
Let’s build our view. We’ll implement a simple interface that shows each poll as a Bootstrap panel with the choices listed in the panel body, and the number of votes for each choice shown at the right edge.
Replace the code in your views/layout.hbs
with this:
<!DOCTYPE html>
<html lang='en'>
<head>
<title>{{title}}</title>
<link rel='stylesheet' href='/stylesheets/style.css'/>
<link rel='stylesheet' href='//netdna.bootstrapcdn.com/bootstrap/3.0.1/css/bootstrap.min.css'/>
</head>
<body>
<div class="container">
{{{body}}}
</div>
</body>
</html>
Put this in your views/index.hbs:
<div class="row">
{{#each polls }}
<div class="col-md-6">
<form onsubmit="vote(event);" id="{{this._id}}">
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">
<span class="glyphicon glyphicon-arrow-right"></span>{{ this.topic }}
</h3>
</div>
<div class="panel-body">
<ul class="list-group">
{{#each this.choices }}
<li class="list-group-item">
<div class="radio">
<label>
<input type="radio" name="optionsRadios" value="{{@index}}">
{{ this.value }}
<div class="alignright" id="vote-count-{{../id}}-{{@index}}">{{ this.votes }}</div>
</label>
</div>
</li>
{{/each}}
</ul>
</div>
<div class="panel-footer">
<input type="submit" id="vote-btn-{{this.id}}" class="btn btn-primary btn-sm" value="Vote">
</div>
</div>
</form>
</div>
{{/each}}
</div>
Lastly, replace the contents of your public/stylesheets/style.css with this:
body {
padding: 50px;
margin-top: 20px;
font: 14px "Lucida Grande", Helvetica, Arial, sans-serif;
}
.panel-body:not(.two-col) {
padding: 0px
}
.glyphicon {
margin-right: 5px;
}
.glyphicon-new-window {
margin-left: 5px;
}
.panel-body .radio, .panel-body .checkbox {
margin-top: 0px;
margin-bottom: 0px;
}
.panel-body .list-group {
margin-bottom: 0;
}
.margin-bottom-none {
margin-bottom: 0;
}
.panel-body .radio label, .panel-body .checkbox label {
display: block;
}
.alignright {
float: right;
}
Let’s implement the voting logic. Laying out the steps we need to perform:
A choice is selected on a certain poll, and the Vote button is clicked. This submits the containing form.
Our registered onsubmit handler retrieves the choice selected and the poll ID from the form and makes an AJAX call to our vote endpoint. The handler also updates the UI to reflect the increased number of votes.
The vote endpoint finds the poll with the specified ID in the database, and increments the number of votes corresponding to the selected choice by 1.
Let’s define our event handler. We’ll pull in Axios for API calls. Add this to your index.hbs
:
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
var vote = function (event) {
event.preventDefault();
var pollId = event.target.id;
var choice = event.target.optionsRadios.value;
axios.post('/' + pollId + '/vote', {choice: choice});
// disable the button, so a user san't vote twice
document.querySelector('#vote-btn-' + pollId).disabled = true;
var voteCount = document.querySelector('#vote-count-' + pollId + '-' + choice);
voteCount.textContent++;
voteCount.style.color = 'green';
voteCount.style.fontWeight = '900';
};
</script>
For the vote endpoint, add this route in your routes/index.js:
router.post('/:pollId/vote', (req, res, next) => {
const choice = req.body.choice;
const identifier = `choices.${choice}.votes`;
Poll.update({_id: req.params.pollId}, {$inc: {[identifier]: 1}}, {}, (err, numberAffected) => {
res.send('');
});
});
In this code snippet, we find the poll with the specified ID then increment the number of votes associated with the specified choice using MongoDB’s $inc operator (you can read more about that here).
You can start your app by running npm start. If you select a choice and click “Vote”, you should see the number of votes displayed for your choice increase.
Messaging with Pusher
The final thing to do is modify our vote endpoint so it sends out a broadcast over Pusher after incrementing the number of votes for the poll. We’ll also need to modify our frontend so that it listens for these broadcasts and updates the UI accordingly.
First off, create a Pusher account if you don’t already have one (it’s free). Then create an app and obtain your app credentials from the app dashboard. Create a file named .env
in the root of your project with the following content:
PUSHER_APP_ID=YOUR_APP_ID
PUSHER_APP_KEY=YOUR_APP_KEY
PUSHER_APP_SECRET=YOUR_APP_SECRET
PUSHER_APP_CLUSTER=YOUR_APP_CLUSTER
Replace YOUR_APP_ID, YOUR_APP_KEY, YOUR_APP_SECRET, and YOUR_APP_CLUSTER with your Pusher app ID, app key, app secret and cluster respectively.
Then add this line to the top of your app.js. This is to setup dotenv so it pulls environment variables from our .env file:
require('dotenv').config();
Modify your routes/index.js
so the vote endpoint looks like this:
router.post('/:pollId/vote', (req, res, next) => {
const choice = req.body.choice;
const identifier = `choices.${choice}.votes`;
Poll.update({_id: req.params.pollId}, {$inc: {[identifier]: 1}}, {}, (err, numberAffected) => {
let Pusher = require('pusher');
let pusher = new Pusher({
appId: process.env.PUSHER_APP_ID,
key: process.env.PUSHER_APP_KEY,
secret: process.env.PUSHER_APP_SECRET,
cluster: process.env.PUSHER_APP_CLUSTER
});
let payload = { pollId: req.params.pollId, choice: choice };
pusher.trigger('poll-events', 'vote', payload, req.body.socketId);
res.send('');
});
});
You’ll notice we include a fourth parameter in our call to pusher.trigger. This is the socket ID, a unique identifier that Pusher assigns to each client connection. This means that every browser window where our voting page is open will have its own socket ID. By passing the socket ID to pusher.trigger, we are ensuring that the client with that ID will not get notified. This is what we want, since that client already updated its view after the Vote button was clicked.
Now, let’s add our listener to our index.hbs:
<script src="https://js.pusher.com/4.1/pusher.min.js"></script>
<script>
var pusher = new Pusher('your_app_key', { cluster: 'your_app_cluster' });
var socketId;
// retrieve the socket ID once we are connected
pusher.connection.bind('connected', function() {
socketId = pusher.connection.socket_id;
});
pusher.subscribe('poll-events')
.bind('vote', function (data) {
var pollId = data.pollId;
var choice = data.choice;
var voteCount = document.querySelector('#vote-count-' + pollId + '-' + choice);
voteCount.textContent++;
// we'll flash the colour for a moment
var color = voteCount.style.color;
setTimeout(function () {
voteCount.style.color = color;
}, 2000);
voteCount.style.color = 'green';
});
</script>
Remember to replace your_app_key with your Pusher app key and your_app_cluster with your app cluster.
We’ll also have to add the socket ID to the POST request we make to the vote endpoint. Modify your vote handler so it looks like this:
var vote = function (event) {
event.preventDefault();
var pollId = event.target.id;
var choice = event.target.optionsRadios.value;
// we add the socket ID to our POST data
axios.post('/' + pollId + '/vote', {choice: choice, socketId: socketId});
document.querySelector('#vote-btn-' + pollId).disabled = true;
var voteCount = document.querySelector('#vote-count-' + pollId + '-' + choice);
voteCount.textContent++;
voteCount.style.color = 'blue';
voteCount.style.fontWeight = '900';
};
Start up your MongoDB server by running mongod, then serve your app with npm start.
Now visit your app on http://localhost:3000 in two browser windows. You should see that as you vote for an option in one window, the change shows up in the other too.
Conclusion
Realtime technologies are a great way to make your app more of a social activity. By seeing the interactions of other users in realtime, users get to feel that they are part of a larger community. In this article, we’ve used Pusher to create a basic social polling app.
13 March 2018
by Shalvah Adebayo