diff --git a/src/controllers/Routes.ts b/src/controllers/Routes.ts index 9b8d491..38cf6bd 100644 --- a/src/controllers/Routes.ts +++ b/src/controllers/Routes.ts @@ -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, needLogin ?: boolean, // Default = true + + // Specific for websockets + wsCallback ?: (req: Request, ws: ws) => Promise | 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}, diff --git a/src/controllers/UserWebSocketController.ts b/src/controllers/UserWebSocketController.ts new file mode 100644 index 0000000..74675b1 --- /dev/null +++ b/src/controllers/UserWebSocketController.ts @@ -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) { + +} \ No newline at end of file diff --git a/src/main.ts b/src/main.ts index d7d4dc3..2dd6240 100644 --- a/src/main.ts +++ b/src/main.ts @@ -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; + } })