Monorepo for Aesthetic.Computer aesthetic.computer
at main 85 lines 2.5 kB view raw
1// Run (Piece) 2// Immediately runs an aesthetic.computer piece via a post-request. 3// Designed to work alongside `vscode-extension`. 4 5/* #region todo 📓 6 + Done 7 - [x] Add a "secret" string for receiving updates on a channel. 8#endregion */ 9 10import { createClient } from "redis"; 11 12const dev = process.env.NETLIFY_DEV; 13const redisConnectionString = process.env.REDIS_CONNECTION_STRING; 14 15async function fun(event) { 16 let status; 17 let out; 18 19 console.log("Running a piece..."); 20 21 // Handle OPTIONS request 22 if (event.httpMethod === "OPTIONS") { 23 return { 24 statusCode: 200, 25 headers: { 26 "Content-Type": "application/json; charset=utf-8", 27 "Access-Control-Allow-Origin": "*", // Specify allowed origins or use '*' for all 28 "Access-Control-Allow-Methods": "POST, OPTIONS", // Specify allowed methods 29 "Access-Control-Allow-Headers": "Content-Type", // Specify allowed headers 30 }, 31 body: JSON.stringify({ status: "OK" }), 32 }; 33 } 34 35 if (event.httpMethod !== "POST") { 36 status = 405; 37 out = { status: "Wrong request type!" }; 38 } else if (event.httpMethod === "POST" && event.path === "/run") { 39 const params = event.queryStringParameters; 40 41 console.log("POST running piece...", params); 42 43 try { 44 const body = JSON.parse(event.body); 45 // Send a redis request or socket message containing the piece code. 46 const client = !dev 47 ? createClient({ url: redisConnectionString }) 48 : createClient(); 49 client.on("error", (err) => console.log("🔴 Redis client error!", err)); 50 await client.connect(); 51 await client.publish( 52 "code", 53 JSON.stringify({ 54 piece: body.piece, 55 source: body.source, 56 codeChannel: body.codeChannel, 57 }), 58 ); 59 out = { result: "Piece code received!" }; 60 console.log(out); 61 return { 62 statusCode: 200, 63 headers: { 64 "Access-Control-Allow-Origin": "*", 65 }, 66 body: "Reloaded!", 67 }; 68 } catch (err) { 69 status = 500; 70 out = { result: `Error receiving piece code: ${err.message}` }; 71 console.log(out); 72 } 73 } 74 75 return { 76 statusCode: status, 77 headers: { 78 "Content-Type": "application/json; charset=utf-8", 79 "Access-Control-Allow-Origin": "*", 80 }, 81 body: JSON.stringify(out), 82 }; 83} 84 85export const handler = fun;