forked from denoland/fresh
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlive_reload.ts
More file actions
39 lines (31 loc) · 1.07 KB
/
live_reload.ts
File metadata and controls
39 lines (31 loc) · 1.07 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
import type { MiddlewareFn } from "../../middlewares/mod.ts";
import { ALIVE_URL } from "../../constants.ts";
// Live reload: Send updates to browser
export function liveReload<T>(): MiddlewareFn<T> {
const revision = Date.now();
return (ctx) => {
const { config, request, url } = ctx;
const aliveUrl = config.basePath + ALIVE_URL;
if (url.pathname === aliveUrl) {
if (request.headers.get("upgrade") !== "websocket") {
return new Response(null, { status: 501 });
}
// TODO: When a change is made the Deno server restarts,
// so for now the WebSocket connection is only used for
// the client to know when the server is back up. Once we
// have HMR we'll actively start sending messages back
// and forth.
const { response, socket } = Deno.upgradeWebSocket(request);
socket.addEventListener("open", () => {
socket.send(
JSON.stringify({
type: "initial-state",
revision,
}),
);
});
return response;
}
return ctx.next();
};
}