File: //matrixSwot/backend/ws.js
const bodyParser = require("body-parser");
const cors = require("cors");
const express = require("express");
const fs = require("fs");
const helmet = require("helmet");
const http = require("http");
const https = require("https");
const logger = require("morgan");
const socketIO = require("socket.io");
const path = require("path");
const routesWs = require("./modules");
const { tokenVerify } = require("./middlewares/token");
const { dbConn } = require("./middlewares/db");
const { tokenDecode } = require("./middlewares/tokenDecode");
require("dotenv-safe").config({
allowEmptyValues: true
});
class App {
constructor() {
this.port = 80;
this.app = express();
this.middlewares();
this.encapsuleSocket();
this.routes();
this.serverOn();
this.socketOn();
}
middlewares() {
this.app.use(express.json());
this.app.use(cors({ credentials: true, origin: true }));
this.app.use(helmet());
this.app.use(logger("dev"));
this.app.use(bodyParser.urlencoded({ extended: true, limit: "200mb" }));
this.app.use(
bodyParser.json({
type: ["json", "application/csp-report"],
limit: "200mb"
})
);
this.app.disable("x-powered-by");
this.app.use(express.static(path.join(__dirname, "public")));
}
async routes() {
this.app.use("/*", tokenVerify, dbConn, routesWs);
}
socketOn() {
this.io.on("connect", async socket => {
const { token } = socket.handshake.query;
const tokenDecoded = await tokenDecode(token);
console.log("user connected => " + socket.id);
});
this.io.on("disconnect", socket => {
console.log(`user disconected => ${socket.id}`);
socket.disconnect();
});
}
encapsuleSocket() {
this.app.use((req, res, next) => {
req.io = this.io;
next();
});
}
serverOn() {
if (process.env.LOCAL === "LOCAL") {
this.port = 3001;
this.server = http.Server(this.app).listen(this.port, () => {
console.log(`server is runing on port ${this.port}`);
});
} else {
this.port = 443;
const options = {
key: fs.readFileSync("ssl-matrixSwot/cert.key"),
cert: fs.readFileSync("ssl-matrixSwot/cert.crt")
};
this.server = https.Server(options, this.app);
this.serverHttp = http.Server(this.app);
this.serverHttp.listen(80, () => {
console.log("server is runing on port 80");
});
}
this.io = socketIO(this.server);
this.io.origins("*:*");
}
}
module.exports = process.env.TEST === "TEST" ? new App().server : new App();