npm install express body-parser jsonwebtoken node-localstorage express-rate-limit
Last active
March 5, 2023 11:49
-
-
Save mike-at-redspace/ee3ebc3f609951d6a539450ff96f6621 to your computer and use it in GitHub Desktop.
Vote API
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const express = require('express'); | |
const bodyParser = require('body-parser'); | |
const jwt = require('jsonwebtoken'); | |
const { LocalStorage } = require('node-localstorage'); | |
const rateLimit = require('express-rate-limit'); | |
const app = express(); | |
const localStorage = new LocalStorage('./database'); | |
const secretKey = 'my-secret-key'; | |
// Use body-parser to parse JSON requests and responses | |
app.use(bodyParser.json()); | |
// Set up rate limiter to prevent spamming | |
const limiter = rateLimit({ | |
windowMs: 60 * 1000, // 1 minute | |
max: 5, // limit each IP to 5 requests per windowMs | |
message: 'Too many requests, please try again later.', | |
}); | |
app.use(limiter); | |
app.post('/vote', (req, res) => { | |
// Verify the JWT token in the Authorization header | |
try { | |
const token = req.headers.authorization.split(' ')[1]; | |
const decoded = jwt.verify(token, secretKey); | |
} catch (err) { | |
return res.status(401).json({ message: 'Invalid or missing token' }); | |
} | |
// Get the vote object and user token from the request body | |
const { vote, userToken } = req.body; | |
// Update the database with the new vote | |
const votes = JSON.parse(localStorage.getItem('votes')) || {}; | |
const existingVote = votes[vote.itemId]; | |
if (existingVote) { | |
existingVote[vote.option] += 1; | |
} else { | |
votes[vote.itemId] = { [vote.option]: 1 }; | |
} | |
localStorage.setItem('votes', JSON.stringify(votes)); | |
// Return the current vote results for the items voted on | |
return res.status(200).json({ votes }); | |
}); | |
app.listen(3000, () => console.log('Server started on port 3000')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment