Snippets Collections
import {Client} from 'pg';
import dotenv from 'dotenv';
dotenv.config();

export const client = new Client({
    database: process.env.DB_NAME,
    user: process.env.DB_USERNAME,
    password: process.env.DB_PASSWORD
});

client.connect();

/--------.env file ------------/
DB_NAME=memo-wall
DB_USERNAME=gordon
DB_PASSWORD=gordon
let sessionMiddleware = expressSession({
  secret: 'Tecky Academy teaches typescript',
  resave: true,
  saveUninitialized: true,
});

app.use(sessionMiddleware);

io.use((socket, next) => {
  let req = socket.request as express.Request;
  let res = req.res!;
  sessionMiddleware(req, res, next as express.NextFunction);
});

io.on('connection', function (socket) {
    if(!socket.request.session.user){
        socket.disconnect()
    }
});
app.post('/apple',(req,res)=>{
    // logic of adding apple.
    if(req.session){
        io.to(`user-${req.session['user'].id}`).emit("new-apple","Congratulations! New Apple Created!");
    }
    res.json({updated:1});
});

io.on('connection', function (socket) {
    ....
    if(socket.request.session['user']){
        socket.join(`user-${socket.request.session['user'].id}`);  
        // One common way is to join the socket to a room named by the `user.id` or other group information.
     }
});
const sessionMiddleware = expressSession({
    secret: 'Tecky Academy teaches typescript',
    resave:true,
    saveUninitialized:true,
    cookie:{secure:false}
});

app.use(sessionMiddleware);

io.use((socket,next)=>{
    let req = socket.request as express.Request
    let res = req.res as express.Response
    sessionMiddleware(req, res, next as express.NextFunction
});
//...
io.on('connection', function (socket) {
    // You can set any values you want to session here.
    const req = socket.request as express.Request;
    req.session['key'] = 'XXX';
    // There is no auto save for session.
    socket.request.session.save();

    // You can also send data using socket.emit() although it is not very useful
    socket.emit('any-key','values');
    socket.on("disconnect",()=>{
        //... rest of the code
    })
});
star

Thu Aug 19 2021 19:17:02 GMT+0000 (Coordinated Universal Time)

#express #typescript #socketio
star

Thu Aug 19 2021 18:56:09 GMT+0000 (Coordinated Universal Time)

#express #typescript #socketio
star

Thu Aug 19 2021 18:45:47 GMT+0000 (Coordinated Universal Time)

#typescript #express #socketio
star

Thu Aug 19 2021 17:56:37 GMT+0000 (Coordinated Universal Time)

#typescript #express #socketio

Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension