Monorepo for Aesthetic.Computer
aesthetic.computer
1// Reload
2// Sends a request to a user piece's current session backend to reload
3// the code for all connected users.
4
5/* #region todo 📓
6#endregion */
7
8import { createClient } from "redis";
9
10const dev = process.env.NETLIFY_DEV;
11const redisConnectionString = process.env.REDIS_CONNECTION_STRING;
12
13async function fun(event, context) {
14 let status;
15 let out;
16 let result = { status: "unsent" };
17
18 if (event.httpMethod !== "POST") {
19 status = 405;
20 out = { status: "Wrong request type!" };
21 } else {
22 status = 200;
23
24 const piece = JSON.parse(event.body).piece;
25 let reloading = piece.startsWith("@"); // Only reload prefixed user pieces.
26
27 if (reloading) {
28 // 1. Connect to redis...
29 const client = !dev
30 ? createClient({ url: redisConnectionString })
31 : createClient();
32 client.on("error", (err) => console.log("🔴 Redis client error!", err));
33 await client.connect();
34
35 // 2. Check to see if a backend is already available...
36 const currentBackend = await client.HGET("backends", piece);
37
38 // ❤️🔥
39 // TODO: To make this faster I could just set a value in redis
40 // and then the jamsocket backend could sub to that message.
41
42 // 3. Send a reload request to the `currentBackend` (ignoring its status).
43 if (currentBackend) {
44 const { got } = await import("got");
45 const base = `https://${currentBackend}.jamsocket.run`;
46
47 result = await got
48 .post({ url: base + "/reload", json: { piece } })
49 .json();
50 } else {
51 // Or don't send a request if there is no backend on record in redis.
52 reloading = false;
53 }
54 }
55
56 out = { piece, reloading, result };
57 }
58
59 return {
60 statusCode: status,
61 headers: {
62 "Content-Type": "application/json; charset=utf-8",
63 //"Access-Control-Allow-Origin": "*",
64 },
65 body: JSON.stringify(out),
66 };
67}
68
69export const handler = fun;