-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
63 lines (59 loc) · 2.1 KB
/
main.js
File metadata and controls
63 lines (59 loc) · 2.1 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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import { serve } from "https://deno.land/std@0.178.0/http/server.ts";
import { serveDir, serveFile } from "https://deno.land/std@0.178.0/http/file_server.ts";
// games
import dragons_cove1 from "./games/dragons_cove1.js";
const mapAndExecuteGameModule = (moduleName, gameContext) => {
switch (moduleName) {
case "dragons_cove1":
return dragons_cove1(gameContext);
default:
throw new Error("Module Not Found.");
}
};
const responseJSON = (data) => {
return new Response(JSON.stringify(data), {
status: 200,
headers: {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*",
},
});
};
serve(async (req) => {
const pathname = new URL(req.url).pathname;
if (pathname.startsWith("/static")) {
return await serveDir(req, {
urlRoot: "static",
fsRoot: "./static",
});
} else if (pathname == "/" || pathname == "index.html") {
return await serveFile(req, "./index.html");
}
// Do dynamic responses
if (pathname.startsWith("/games/")) {
const gamename = pathname.substring("/games/".length).replaceAll(".", "_");
if (req.method == "POST") {
try {
const data = mapAndExecuteGameModule(gamename, await req.json());
if (data instanceof Promise) {
return responseJSON(await data);
} else {
return responseJSON(data);
}
} catch (err) {
console.error(err);
}
} else if (req.method == "OPTIONS") {
return new Response("200 OK", {
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "POST, OPTIONS",
"Access-Control-Allow-Headers": req.headers.get("Access-Control-Request-Headers"),
"Access-Control-Max-Age": "86400",
}
});
}
return new Response("Failed.", { status: 500 });
}
return new Response();
});