seanpmaxwell/overnight

right way to use socket.io

Closed this issue · 4 comments

Hi, this library has a right way to use socket.io inside @Controlller ?

Haven't used socket.io so can't say. Just checked the docs here, https://socket.io/docs/#Using-with-Express. I don't see how OvernightJS would make any difference.

the way I managed to make the socket work in conjunction with the overnight is as follows:

export class AppServer extends Server {
    private readonly logger: Logger;
    private close: http.Server;

    constructor() {
        super();
        this.logger = new Logger();
        this.logger.rmTimestamp = true;
        this.app.use(cors());
        this.app.use(compression());
        this.app.use(helmet());
        this.app.use(bodyParser.json());
        this.app.use(bodyParser.urlencoded({extended: true}));
        this.app.use((req: Request, res: Response, next: NextFunction) => {
            res.setHeader('Content-type', 'application/json');
            res.setHeader('Accept', 'application/json');
            res.setHeader('Access-Control-Allow-Origin', '*');
            res.setHeader('Access-Control-Allow-Credentials', 'true');
            next();
        });
        this.mongoConnection();
        this.setupControllers();
    }

    stop() {
        this.close.close();
    }

    start() {
        const port = 4000;
        this.close = this.app.listen(port, () => {
            this.logger.info('Server listening on port: ' + port);
        });
    }

    initSocket() {
        this.logger.info('initializing socket');
        const io = require('socket.io')(this.close);
        io.on('connection', (socket: Socket) => {
            this.logger.info('user connected');
            socket.on('chat', (data: any) => {
                io.emit('chat', data);
            });
        });
    }

    private setupControllers() {
        this.logger.rmTimestamp = true;
        this.logger.info('\nRegistering controllers');
        super.addControllers([
            new ChatController(),
        ]);
    }

    private mongoConnection() {
        const url = `${process.env.MONGODB_URL}:${process.env.MONGO_PORT}`;
        connect(process.env.MONGODB_URI || url,
            {
                useNewUrlParser: true,
                useFindAndModify: false,
                useCreateIndex: true,
                dbName: process.env.MONGO_DB_NAME,
                user: process.env.MONGO_USER,
                pass: process.env.MONGO_PASSWORD,
            },
        ).catch((err) => {
            throw err;
        });
    }
}

and my startup server

const server = new AppServer();
server.start();
server.initSocket();

Thanks for posting that. I'm sure some will find it useful.