summaryrefslogtreecommitdiff
path: root/server.js
blob: 1f5db18316e09b69be0d374403b6946010978b32 (plain)
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
const express = require("express");
const http = require("http");
const path = require("path");
const { Server } = require("socket.io");

const app = express();
const server = http.createServer(app);
const io = new Server(server);

app.use(express.json());
app.use(express.static(path.join(__dirname, "public")));

const state = {
  entries: ["Alice", "Bob", "Charlie", "Diana", "Eve", "Frank"],
  selectedWinner: null,
  lastSpin: null,
};

const normalizeEntries = (entries) => {
  if (!Array.isArray(entries) || entries.length < 2) {
    return null;
  }

  const cleaned = entries
    .map((entry) => String(entry).trim())
    .filter((entry) => entry.length > 0);

  if (cleaned.length < 2) {
    return null;
  }

  return cleaned;
};

const emitState = () => {
  io.emit("state", {
    entries: state.entries,
    selectedWinner: state.selectedWinner,
    lastSpin: state.lastSpin,
  });
};

io.on("connection", (socket) => {
  socket.emit("state", {
    entries: state.entries,
    selectedWinner: state.selectedWinner,
    lastSpin: state.lastSpin,
  });
});

app.get("/api/state", (_req, res) => {
  res.json({
    entries: state.entries,
    selectedWinner: state.selectedWinner,
    lastSpin: state.lastSpin,
  });
});

app.post("/api/entries", (req, res) => {
  const entries = normalizeEntries(req.body?.entries);
  if (!entries) {
    return res.status(400).json({
      error: "entries must be an array with at least 2 non-empty names",
    });
  }

  state.entries = entries;

  if (state.selectedWinner && !state.entries.includes(state.selectedWinner)) {
    state.selectedWinner = null;
  }

  emitState();

  return res.json({
    ok: true,
    entries: state.entries,
  });
});

app.post("/api/spin", (req, res) => {
  const winner = String(req.body?.winner || "").trim();

  if (!winner) {
    return res.status(400).json({ error: "winner is required" });
  }

  if (!state.entries.includes(winner)) {
    return res.status(400).json({
      error: "winner must be one of the configured entries",
      entries: state.entries,
    });
  }

  state.selectedWinner = winner;
  state.lastSpin = {
    winner,
    requestedAt: new Date().toISOString(),
  };

  io.emit("spin", state.lastSpin);
  emitState();

  return res.json({
    ok: true,
    spin: state.lastSpin,
  });
});

const port = Number(process.env.PORT || 3000);

server.listen(port, () => {
  console.log(`Wheel server running on http://localhost:${port}`);
});