frontend: gateway reconnect + add frontend directory to express server

This commit is contained in:
hippoz 2022-04-14 16:56:01 +03:00
parent a9a4cdbb5c
commit d21408ac63
No known key found for this signature in database
GPG key ID: 7C52899193467641
4 changed files with 29 additions and 10 deletions

View file

@ -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));

View file

@ -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

View file

@ -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) {

View file

@ -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"));
};