diff --git a/frontend/src/gateway.js b/frontend/src/gateway.js index a247f41..cf177d1 100644 --- a/frontend/src/gateway.js +++ b/frontend/src/gateway.js @@ -21,16 +21,28 @@ export default { heartbeatInterval: null, user: null, channels: null, + reconnectDelay: 400, + reconnectTimeout: null, init() { + const token = getAuthToken(); + if (!token) { + return false; + } this.ws = new WebSocket(getItem("gatewayBase")); - this.ws.onmessage = (message) => { - const payload = JSON.parse(message); + this.ws.onopen = () => { + if (this.reconnectTimeout) { + clearTimeout(this.reconnectTimeout); + } + this.reconnectDelay = 400; + }; + this.ws.onmessage = (event) => { + const payload = JSON.parse(event.data); switch (payload.t) { case GatewayPayloadType.Hello: { this.send({ t: GatewayPayloadType.Authenticate, - d: getAuthToken() + d: token }); this.heartbeatInterval = setInterval(() => { @@ -49,13 +61,19 @@ export default { } }; this.ws.onclose = () => { + this.reconnectDelay *= 2; this.authenticated = false; this.user = null; this.channels = null; if (this.heartbeatInterval) { clearInterval(this.heartbeatInterval); } + this.reconnectTimeout = setTimeout(() => { + this.init(); + }, this.reconnectDelay); }; + + return true; }, send(data) { return this.ws.send(JSON.stringify(data)); diff --git a/frontend/src/main.js b/frontend/src/main.js index 2624668..5dd9d09 100644 --- a/frontend/src/main.js +++ b/frontend/src/main.js @@ -1,4 +1,9 @@ import App from './components/App.svelte'; +import gateway from './gateway'; +import { initStorageDefaults } from './storage'; + +initStorageDefaults(); +gateway.init(); const app = new App({ target: document.body diff --git a/frontend/src/storage.js b/frontend/src/storage.js index 4e53bf8..d9e1bb0 100644 --- a/frontend/src/storage.js +++ b/frontend/src/storage.js @@ -14,10 +14,7 @@ const dummyProvider = { }; function getProvider() { - if (!window.localStorage || !window.localStorage.getItem || !window.localStorage.setItem) { - return dummyProvider; - } - return window.localStorage; + return window.localStorage || dummyProvider; } export function getItem(key) { diff --git a/src/server.ts b/src/server.ts index 58d9972..210f5f0 100644 --- a/src/server.ts +++ b/src/server.ts @@ -1,13 +1,12 @@ -import { Application, json } from "express"; +import express, { Application, json } from "express"; import usersRouter from "./routes/api/v1/users"; import channelsRouter from "./routes/api/v1/channels"; import messagesRouter from "./routes/api/v1/messages"; export default function(app: Application) { - app.get("/", (req, res) => res.send("hello!")); - app.use(json()); app.use("/api/v1/users", usersRouter); app.use("/api/v1/channels", channelsRouter); app.use("/api/v1/messages", messagesRouter); + app.use("/", express.static("frontend/public")); };