refactor: tidy

This commit is contained in:
cha0s 2024-06-13 21:00:40 -05:00
parent e9da3871a4
commit c1758ef3d6

View File

@ -19,16 +19,11 @@ function onUpgrade(request, socket, head) {
} }
} }
export default async function listen(server) { let engine;
server.on('upgrade', onUpgrade); let onConnect;
class SocketServer extends Server { function createOnConnect(engine) {
transmit(ws, packed) { ws.send(packed); } onConnect = async (ws) => {
}
let onConnect;
function makeOnConnect(engine) {
return async (ws) => {
ws.on('close', () => { ws.on('close', () => {
engine.disconnectPlayer(ws); engine.disconnectPlayer(ws);
}) })
@ -37,27 +32,40 @@ export default async function listen(server) {
}); });
await engine.connectPlayer(ws); await engine.connectPlayer(ws);
}; };
} wss.on('connection', onConnect);
}
let engine; class SocketServer extends Server {
async function makeEngine(Engine) { transmit(ws, packed) { ws.send(packed); }
const engine = new Engine(SocketServer); }
async function createEngine(Engine) {
engine = new Engine(SocketServer);
await engine.load(); await engine.load();
engine.start(); engine.start();
return engine; return engine;
} }
engine = await makeEngine(Engine); async function remakeServer(Engine) {
wss.on('connection', onConnect = makeOnConnect(engine)); if (onConnect) {
if (import.meta.hot) {
import.meta.hot.accept('./engine/engine.js', async ({default: Engine}) => {
wss.off('connection', onConnect); wss.off('connection', onConnect);
}
if (engine) {
for (const [connection] of engine.connectedPlayers) { for (const [connection] of engine.connectedPlayers) {
connection.close(); connection.close();
} }
engine = await makeEngine(Engine);
wss.on('connection', onConnect = makeOnConnect(engine));
});
} }
createOnConnect(await createEngine(Engine));
}
await remakeServer(Engine);
if (import.meta.hot) {
import.meta.hot.accept('./engine/engine.js', async ({default: Engine}) => {
await remakeServer(Engine);
});
}
export default async function listen(server) {
server.on('upgrade', onUpgrade);
} }