Add Fastify + EJS Templating

This commit is contained in:
Holly Stubbs 2024-04-22 16:05:42 +01:00
parent 3159fc9c0a
commit 724e344cf5
Signed by: tgpholly
GPG key ID: B8583C4B7D18119E
8 changed files with 856 additions and 42 deletions

View file

@ -1,5 +1,8 @@
{ {
"port": 38195, "ports": {
"http": 38194,
"ws": 39195
},
"database": { "database": {
"address": "localhost", "address": "localhost",
"port": 3306, "port": 3306,

View file

@ -1,5 +1,8 @@
import { createReader, createWriter, Endian } from "bufferstuff"; import { createReader, createWriter, Endian } from "bufferstuff";
import { WebSocketServer } from "ws"; import { WebSocketServer } from "ws";
import Fastify from "fastify";
import FastifyView from "@fastify/view";
import EJS from "ejs";
import Config from "./objects/Config"; import Config from "./objects/Config";
import FunkyArray from "./objects/FunkyArray"; import FunkyArray from "./objects/FunkyArray";
import RemoteUser from "./objects/RemoteUser"; import RemoteUser from "./objects/RemoteUser";
@ -13,9 +16,36 @@ const users = new FunkyArray<string, RemoteUser>();
new Database(Config.database.address, Config.database.port, Config.database.username, Config.database.password, Config.database.name); new Database(Config.database.address, Config.database.port, Config.database.username, Config.database.password, Config.database.name);
const server = new WebSocketServer({ const fastify = Fastify({
port: Config.port logger: false
}, () => Console.printInfo(`Server listening at ${Config.port}`)); });
fastify.register(FastifyView, {
engine: {
ejs: EJS
}
})
fastify.get("/", async (req, res) => {
// @ts-ignore
return res.view("templates/index.ejs", { });
});
const websocketServer = new WebSocketServer({
port: Config.ports.ws
}, () => {
Console.printInfo(`WebsocketServer listening at ws://localhost:${Config.ports.ws}`);
fastify.listen({ port: Config.ports.http }, (err, address) => {
if (err) {
Console.printError(`Error occured while spinning up fastify:\n${err}`);
process.exit(1);
}
Console.printInfo(`Fastify listening at ${address.replace("[::1]", "localhost")}`);
Console.printInfo("MultiProbe is ready to go!");
});
});
function sendToAllButSelf(user:RemoteUser, data:Buffer) { function sendToAllButSelf(user:RemoteUser, data:Buffer) {
users.forEach(otherUser => { users.forEach(otherUser => {
@ -33,7 +63,7 @@ function sendToAll(user:RemoteUser, data:Buffer) {
}); });
} }
server.on("connection", (socket) => { websocketServer.on("connection", (socket) => {
const myUUID = crypto.randomUUID(); const myUUID = crypto.randomUUID();
let user:RemoteUser; let user:RemoteUser;
@ -97,8 +127,9 @@ server.on("connection", (socket) => {
return; return;
} }
if ((Date.now() - user.lastPingReset) >= 1000) { if ((performance.now() - user.lastPingReset) >= 1000) {
user.allowedPings = 10; user.allowedPings = 10;
user.lastPingReset = performance.now();
} }
if (user.allowedPings > 0) { if (user.allowedPings > 0) {
@ -114,3 +145,22 @@ server.on("connection", (socket) => {
} }
}); });
}); });
let isShuttingDown = false;
function shutdown() {
if (isShuttingDown) {
return;
}
isShuttingDown = true;
Console.printInfo("Shutting down...");
websocketServer.close(async () => {
await fastify.close();
Console.cleanup();
console.log("Goodbye!");
});
}
process.on("SIGQUIT", shutdown);
process.on("SIGINT", shutdown);
process.on("SIGUSR2", shutdown);

View file

@ -5,11 +5,15 @@ const config = JSON.parse(readFileSync("./config.json").toString());
export default class Config { export default class Config {
public constructor() { throw new Error("Static Class"); } public constructor() { throw new Error("Static Class"); }
public static port:number = config.port; public static ports:ConfigPorts = config.ports;
public static database:ConfigDatabase = config.database; public static database:ConfigDatabase = config.database;
} }
interface ConfigPorts {
http: number,
ws: number
}
interface ConfigDatabase { interface ConfigDatabase {
address: string, address: string,
port: number, port: number,

786
server/package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -15,12 +15,16 @@
"author": "tgpholly", "author": "tgpholly",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@fastify/view": "^9.0.0",
"bufferstuff": "^1.5.1", "bufferstuff": "^1.5.1",
"ejs": "^3.1.10",
"fastify": "^4.26.2",
"hsconsole": "^1.0.2", "hsconsole": "^1.0.2",
"mysql2": "^3.9.7", "mysql2": "^3.9.7",
"ws": "^8.16.0" "ws": "^8.16.0"
}, },
"devDependencies": { "devDependencies": {
"@types/ejs": "^3.1.5",
"@types/node": "^20.12.7", "@types/node": "^20.12.7",
"@types/ws": "^8.5.10", "@types/ws": "^8.5.10",
"@vercel/ncc": "^0.38.1", "@vercel/ncc": "^0.38.1",

View file

@ -0,0 +1,4 @@
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.3/js/bootstrap.min.js" integrity="sha512-ykZ1QQr0Jy/4ZkvKuqWn4iF3lqPZyij9iRv6sGqLRdTPkY69YX6+7wvVGmsdBbiIfN/8OdsI7HABjvEok6ZopQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
</body>
</html>

View file

@ -0,0 +1,26 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.3/css/bootstrap.min.css" integrity="sha512-jnSuA4Ss2PkkikSOLtYs8BlYIeeIK1h99ty4YfvRPAlzr377vr3CXDb7sb7eEEBYjDtcYj+AjBH3FLv5uSJuXg==" crossorigin="anonymous" referrerpolicy="no-referrer" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js" integrity="sha512-v2CJ7UaYy4JwqLDIrZUI/4hqeoQieOmAZNXBeQyjo21dadnwR+8ZaIJVT8EE2iyI61OV8e6M8PP2/4hpQINQ/g==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
</head>
<body>
<nav class="navbar navbar-expand-lg bg-body-tertiary">
<div class="container-fluid">
<a class="navbar-brand" href="/">MultiProbe</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav me-auto mb-2 mb-lg-0">
</ul>
</div>
</div>
</nav>
<div class="container pt-3">

View file

@ -0,0 +1,3 @@
<%- include("base/header") -%>
<h1>Hello world!</h1>
<%- include("base/footer") -%>