0

I have a node.js and TSOA project I am wondering if anyone has tried to inject a socket.io reference into all of the routes?

Here is my setup:

import * as express from 'express';
import * as cors from 'cors';
import * as bodyparser from '../vender/body-parser';
import * as socketio from 'socket.io';

import { requestLoggerMiddleware } from './request.logger.middleware';


import { RegisterRoutes } from './routes/routes';
import * as swaggerUi from 'swagger-ui-express';

const app = express();
app.use(
  cors({
    origin: ['http://localhost:4200', '*'],
    credentials: true,
  })
);

app.use(bodyparser.json());
app.use(requestLoggerMiddleware);
RegisterRoutes(app);  // <- These are auto generated don't touch!!!

let http = require('http').Server(app);
let io = require('socket.io')(http);
io.on('connection', function (socket: any) {
  console.log('a user connected');
  socket.on("message", function(message: any) {
    console.log(message);
    socket.emit('message', 'testtest');
  });
});

It would be amazing if i could get access to the io object in all of the routes without having to re-define it every route. Any idea if this is possible?

Thanks all!

Kevin192291
  • 1,925
  • 4
  • 26
  • 43
  • Did you find a solution to this? – t348575 Mar 10 '21 at 04:52
  • I did, and that was basically to move this into its own file that all of my constructors were derived from, Since that time I moved to Nest.js, Nx, and Angular, Since then I have found all of the issues like these go away. – Kevin192291 Mar 10 '21 at 18:53

1 Answers1

0

You could store it in the app object in index.js like this

app.set('socketio', io);

And then access it through the request object from each route

const io = request.app.get('socketio')
Hugo
  • 1
  • 1