-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
78 lines (64 loc) · 2.42 KB
/
Copy pathserver.js
File metadata and controls
78 lines (64 loc) · 2.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
require("dotenv").config({ quiet: true });
const express = require("express");
const path = require("path");
const { sendVerificationCode, checkVerificationCode } = require("./lib/verify");
const app = express();
const PORT = process.env.PORT || 3000;
app.use(express.json());
app.use(express.static(path.join(__dirname, "public")));
const names = [
{ id: 1, name: "Tuna Fish", votes: 5 },
{ id: 2, name: "Small Bear", votes: 3 },
{ id: 3, name: "Miss Jenkins", votes: 1 },
];
// Tracks which phone numbers have already voted, to enforce one vote per number.
const votedPhoneNumbers = new Set();
app.get("/api/names", (req, res) => {
const sorted = [...names].sort((a, b) => b.votes - a.votes);
res.json(sorted);
});
app.post("/api/verify/send", async (req, res) => {
const phoneNumber = typeof req.body.phoneNumber === "string" ? req.body.phoneNumber.trim() : "";
if (!phoneNumber) {
return res.status(400).json({ error: "A phone number is required." });
}
if (votedPhoneNumbers.has(phoneNumber)) {
return res.status(400).json({ error: "This phone number has already voted." });
}
try {
await sendVerificationCode(phoneNumber);
res.status(200).json({ sent: true });
} catch (err) {
res.status(400).json({ error: "Could not send a verification code to that number." });
}
});
app.post("/api/names/:id/vote", async (req, res) => {
const id = Number(req.params.id);
const entry = names.find((n) => n.id === id);
const phoneNumber = typeof req.body.phoneNumber === "string" ? req.body.phoneNumber.trim() : "";
const code = typeof req.body.code === "string" ? req.body.code.trim() : "";
if (!entry) {
return res.status(404).json({ error: "Name not found." });
}
if (!phoneNumber || !code) {
return res.status(400).json({ error: "A phone number and verification code are required." });
}
if (votedPhoneNumbers.has(phoneNumber)) {
return res.status(400).json({ error: "This phone number has already voted." });
}
let approved;
try {
approved = await checkVerificationCode(phoneNumber, code);
} catch (err) {
return res.status(400).json({ error: "Could not check that verification code." });
}
if (!approved) {
return res.status(400).json({ error: "Incorrect or expired verification code." });
}
votedPhoneNumbers.add(phoneNumber);
entry.votes += 1;
res.json(entry);
});
app.listen(PORT, () => {
console.log(`Puppy naming contest running on port ${PORT}`);
});