diff options
author | Madeline <46743919+MaddyUnderStars@users.noreply.github.com> | 2022-09-25 18:24:21 +1000 |
---|---|---|
committer | Madeline <46743919+MaddyUnderStars@users.noreply.github.com> | 2022-09-25 23:35:18 +1000 |
commit | 0d23eaba09a4878520bf346af4cead90d76829fc (patch) | |
tree | d930eacceff0b407b44abe55f01d8e3c5dfbfa34 /src/gateway/Server.ts | |
parent | Allow edited_timestamp to passthrough in handleMessage (diff) | |
download | server-0d23eaba09a4878520bf346af4cead90d76829fc.tar.xz |
Refactor to mono-repo + upgrade packages
Diffstat (limited to 'src/gateway/Server.ts')
-rw-r--r-- | src/gateway/Server.ts | 63 |
1 files changed, 63 insertions, 0 deletions
diff --git a/src/gateway/Server.ts b/src/gateway/Server.ts new file mode 100644 index 00000000..7e1489be --- /dev/null +++ b/src/gateway/Server.ts @@ -0,0 +1,63 @@ +import "missing-native-js-functions"; +import dotenv from "dotenv"; +dotenv.config(); +import { closeDatabase, Config, initDatabase, initEvent } from "@fosscord/util"; +import ws from "ws"; +import { Connection } from "./events/Connection"; +import http from "http"; + +export class Server { + public ws: ws.Server; + public port: number; + public server: http.Server; + public production: boolean; + + constructor({ + port, + server, + production, + }: { + port: number; + server?: http.Server; + production?: boolean; + }) { + this.port = port; + this.production = production || false; + + if (server) this.server = server; + else { + this.server = http.createServer(function (req, res) { + res.writeHead(200).end("Online"); + }); + } + + this.server.on("upgrade", (request, socket, head) => { + // @ts-ignore + this.ws.handleUpgrade(request, socket, head, (socket) => { + this.ws.emit("connection", socket, request); + }); + }); + + this.ws = new ws.Server({ + maxPayload: 4096, + noServer: true, + }); + this.ws.on("connection", Connection); + this.ws.on("error", console.error); + } + + async start(): Promise<void> { + await initDatabase(); + await Config.init(); + await initEvent(); + if (!this.server.listening) { + this.server.listen(this.port); + console.log(`[Gateway] online on 0.0.0.0:${this.port}`); + } + } + + async stop() { + closeDatabase(); + this.server.close(); + } +} |