Skip to content

Instantly share code, notes, and snippets.

@mdmunir
Created May 5, 2020 05:12
Show Gist options
  • Select an option

  • Save mdmunir/3a31a12e84a96d9a5a05580a7f833e89 to your computer and use it in GitHub Desktop.

Select an option

Save mdmunir/3a31a12e84a96d9a5a05580a7f833e89 to your computer and use it in GitHub Desktop.
const PORT = process.env.PORT || 3001;
const STR_REGEX = 'socket\\-[a-z0-9]+';
var express = require('express');
var app = express();
var http = require('http').createServer(app);
var io = require('socket.io')(http, {
handlePreflightRequest: (req, res) => {
const headers = {
"Access-Control-Allow-Headers": "Content-Type, Authorization",
"Access-Control-Allow-Origin": req.headers.origin,
"Access-Control-Allow-Credentials": true
};
res.writeHead(200, headers);
res.end();
}
});
// endpoint
app.use(express.json());
app.post(`/:ns(${STR_REGEX})`, function (req, res) {
var ns = io.of(req.params.ns);
if (req.body.users) {
req.body.users.forEach(function (id) {
ns.to(`user-${id}`).volatile.emit(req.body.name, req.body.data);
});
} else if (req.body.room) {
ns.to(req.body.room).volatile.emit(req.body.name, req.body.data);
} else {
ns.volatile.emit(req.body.name, req.body.data);
}
res.json({status: true});
});
app.get(`/:ns(${STR_REGEX})`, function (req, res) {
var ns = io.of(req.params.ns);
ns.clients((error, clients) => {
res.json(error ? {error: error} : {count: clients.length});
});
});
http.listen(PORT, function () {
console.log('listening on *:' + PORT);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment