1
0
mirror of https://gitlab.com/comunic/comunicapiv2 synced 2024-12-26 13:38:52 +00:00

Listen for websockets

This commit is contained in:
Pierre HUBERT 2020-03-29 17:52:28 +02:00
parent a58452af3e
commit 70a5c910d2
3 changed files with 48 additions and 7 deletions

View File

@ -16,6 +16,9 @@ import { CommentsController } from "./CommentsController";
import { LikesController } from "./LikesController";
import { SurveyController } from "./SurveyController";
import { SettingsController } from "./SettingsController";
import { Request } from "express";
import * as ws from 'ws';
import { UserWS } from "./UserWebSocketController";
/**
* Controllers routes
@ -25,7 +28,8 @@ import { SettingsController } from "./SettingsController";
export enum RouteType {
POST, // Default
GET
GET,
WS, // Special: WebSockets
}
export interface Route {
@ -33,10 +37,16 @@ export interface Route {
path: string,
cb: (req : RequestHandler) => Promise<void> | void,
needLogin ?: boolean, // Default = true
// Specific for websockets
wsCallback ?: (req: Request, ws: ws) => Promise<void> | void
}
export const Routes : Route[] = [
// Main user websocket
{type: RouteType.WS, path: "/ws", cb: () => {throw Error()}, wsCallback: UserWS },
// Welcome controller
{type: RouteType.GET, path: "/", cb: WelcomeController.HomeMessage, needLogin: false},

View File

@ -0,0 +1,11 @@
/**
* User websocket controller
*
* @author Pierre Hubert
*/
import * as ws from 'ws';
import { Request } from 'express';
export async function UserWS(req: Request, ws: ws) {
}

View File

@ -4,6 +4,8 @@ import { DatabaseHelper } from "./helpers/DatabaseHelper";
import { Routes, RouteType } from './controllers/Routes';
import { RequestHandler } from './entities/RequestHandler';
import * as fileUpload from 'express-fileupload';
import * as expressWs from 'express-ws';
import * as ws from 'ws';
/**
* Main project script
@ -22,7 +24,7 @@ async function init() {
await DatabaseHelper.connect();
// Start HTTP Server
const app = express();
const app = expressWs(express()).app;
app.use(express.urlencoded({extended: true}));
@ -53,11 +55,29 @@ async function init() {
}
};
if(route.type == RouteType.GET)
app.get(route.path, cb);
else
app.post(route.path, cb);
// WebSocket callback
const wsCB = async (ws: ws, req: express.Request) => {
try {
await route.wsCallback(req, ws);
} catch(e) {
console.error(e);
}
}
// Call the appropriate function
switch(route.type) {
case RouteType.GET:
app.get(route.path, cb);
break;
case RouteType.WS:
app.ws(route.path, wsCB);
break;
default:
app.post(route.path, cb);
break;
}
})