diff --git a/backend-app/app.ts b/backend-app/app.ts index e0c14a1..bc7821c 100644 --- a/backend-app/app.ts +++ b/backend-app/app.ts @@ -17,8 +17,8 @@ import cookieParser from 'cookie-parser'; // import routesVersioning from 'express-routes-versioning'; // import indexRouter from './routes/index'; import { RegisterRoutes } from './routes'; -import TaskEmitter from '@root/utils/TaskEmitter'; -import { expressAuthentication } from './middlewares/authentications'; +import notification_controller from './controllers/notification_controller'; + const app = express(); // use json as default format @@ -71,29 +71,7 @@ app.use(handleAPIVersion); // handle bearer token app.use(bearerToken()); -app.get( - '/streams', - async (req, res, next) => { - await expressAuthentication(req, 'jwt'); - next(); - }, - (req, res) => { - TaskEmitter.registerClient(req, res); - console.log('Client connnected...'); - res.writeHead(200, { - 'Content-Type': 'text/event-stream', - 'Cache-Control': 'no-cache', - 'Content-Encoding': 'none', - Connection: 'keep-alive', - }); - TaskEmitter.listenIncomingNotification(); - res.on('close', () => { - console.log('Client disconnected.'); - TaskEmitter.removeConnectedClient(String(req.user._id)); - res.end(); - }); - } -); +app.get('/streams', notification_controller); app.get('/', (_req: Request, res: Response) => { res.status(200).json({ diff --git a/backend-app/controllers/notification_controller.ts b/backend-app/controllers/notification_controller.ts new file mode 100644 index 0000000..2e5f6ce --- /dev/null +++ b/backend-app/controllers/notification_controller.ts @@ -0,0 +1,29 @@ +import { IReq } from '@root/interfaces/vendors'; +import { expressAuthentication } from '@root/middlewares/authentications'; +import TaskEmitter from '@root/utils/TaskEmitter'; +import { NextFunction, Response } from 'express'; + +export default [ + async (req: IReq, res: Response, next: NextFunction) => { + try { + await expressAuthentication(req, 'jwt'); + next(); + } catch (err) { + res.json(err.message); + } + }, + (req: IReq, res: Response) => { + TaskEmitter.registerClient(req, res); + res.writeHead(200, { + 'Content-Type': 'text/event-stream', + 'Cache-Control': 'no-cache', + 'Content-Encoding': 'none', + Connection: 'keep-alive', + }); + TaskEmitter.listenIncomingNotification(); + res.on('close', () => { + TaskEmitter.removeConnectedClient(String(req.user._id)); + res.end(); + }); + }, +];