aboutsummaryrefslogtreecommitdiff
path: root/examples/bun-hot-websockets.js
blob: 7cdaf0f0213577c1bf99d49a26a2e7b1d3f507dc (plain) (blame)
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
// To run this example:
//
//   bun --hot bun-hot-websockets.js
//

const css = ([inner]) => {
  return inner;
};

const styles = css`
  #bun {
    margin: 0 auto;
    margin-top: 200px;
    object-fit: cover;
  }
  html,
  body {
    margin: 0;
    padding: 0;
  }
  body {
    background: #f1239f;
    font-family: "Inter", sans-serif;
    display: flex;
    align-items: center;
    justify-content: center;
    align-content: center;
    color: white;
  }
  h1 {
    padding: 0;
    text-align: center;
    font-size: 3rem;
    -webkit-text-stroke: 2px black;
  }
  * {
    box-sizing: border-box;
  }
`;

export default {
  websocket: {
    message(ws, msg) {
      ws.send(styles);
    },
  },
  fetch(req, server) {
    if (req.url.endsWith("/hot")) {
      if (server.upgrade(req))
        return new Response("", {
          status: 101,
        });
    }

    return new Response(
      `
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8">
        <title>WebSockets</title>
    </head>
    <body>
      <style></style>
        <script>
            const ws = new WebSocket("ws://localhost:3000/hot");
            const style = document.querySelector("style");
            ws.onmessage = (e) => {
              style.innerHTML = e.data;
            };
            setInterval(() => {
                ws.send("ping");
            }, 8);
        </script>
        <div id="app">
            <img src="https://bun.sh/logo.svg" alt="Bun" id='bun'  />
            <h1>bun --hot websockets</h1>
        </div>
    </body>
        
    `,
      {
        headers: {
          "Content-Type": "text/html; charset=utf-8",
        },
      },
    );
  },
};