-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
57 lines (45 loc) · 1.46 KB
/
index.js
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
import express from "express";
import { getUserInfo } from "@replit/repl-auth";
const app = express();
import Vote from "./models/Vote.js";
import encrypted from "./utils/encrypted.js";
import vote from "./utils/vote.js";
import getAllVotes from "./utils/getAllVotes.js";
app.use(express.static("public"));
app.set("view engine", "ejs");
app.use((req, res, next) => {
res.append("Access-Control-Allow-Origin", "*");
next();
});
app.get("/", async (req, res) => {
const user = getUserInfo(req);
const loggedIn = !!user;
const votes = await getAllVotes();
const userAlreadyVoted = loggedIn
? (await encrypted(user.id)) === null
: false;
res.render("index", { loggedIn, votes, userAlreadyVoted });
});
app.post("/vote/:option", async (req, res) => {
const user = getUserInfo(req);
if (user) {
const success = await vote(user.id, parseInt(req.params.option));
if (success) {
const votes = await getAllVotes();
return res.status(200).json({ ...votes, message: "Success." });
} else {
return res.status(400).json({ message: "There was an error in voting." });
}
} else {
return res.status(401).json({ message: "You must be logged in to vote." });
}
});
app.get("/api", async (req, res) => {
const votes = await getAllVotes();
return res.status(200).json(votes);
});
app.get("/api/data", async (req, res) => {
const votes = await Vote.findAll({ raw: true });
return res.status(200).json(votes);
});
app.listen(8080);