You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

72 lines
2.0 KiB

4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
  1. const app = require('express')();
  2. const bodyParser = require('body-parser');
  3. const server = require('http').createServer(app);
  4. const io = require('socket.io')(server, {
  5. cors: {
  6. origin: "http://127.0.0.1:3000",
  7. methods: ["GET", "POST"],
  8. }
  9. });
  10. const redisAdapter = require('socket.io-redis');
  11. const axios = require('axios');
  12. //setup redis
  13. io.adapter(redisAdapter({host: '127.0.0.1', port: 6379, password: 'root'}));
  14. // parse application/x-www-form-urlencoded
  15. app.use(bodyParser.urlencoded({ extended: false }));
  16. // parse application/json
  17. app.use(bodyParser.json());
  18. // server main route
  19. app.get('/', (req, res) => {
  20. res.sendFile(__dirname + '/static/index.html');
  21. });
  22. io.on('connection', async (socket) => {
  23. const auth = socket.handshake.query.auth;
  24. const business = socket.handshake.query.business;
  25. const AuthStr = 'Bearer '.concat(auth);
  26. console.log('user conencted : ', auth);
  27. if (auth !== undefined) {
  28. axios
  29. .get('http://127.0.0.1:80/user/v1/businesses/'+business, {
  30. headers: { Authorization: AuthStr }
  31. })
  32. .then((res) => {
  33. // console.log(res.data)
  34. if (res.status === 200) {
  35. console.log('user joined to,', 'room-'+business);
  36. socket.join('room-'+business);
  37. }
  38. })
  39. .catch((error) => {
  40. console.error(error)
  41. })
  42. }
  43. });
  44. // app.get('/:room/:event', function (req, res) {
  45. // console.log(req.query);
  46. // // io.to(req.params.room).emit(req.params.event, req.params.message);
  47. // res.send('done');
  48. // });
  49. app.post('/emit/:room', function (req, res) {
  50. // console.log(req.body);
  51. console.log('room is :','room-' + req.params.room);
  52. console.log('message',req.body.data);
  53. io.to('room-' + req.params.room).emit('room-event', req.body.data);
  54. // console.log(req.body.data);
  55. // res.json(req.body.data)
  56. res.send('done');
  57. });
  58. server.listen(3030, () => {
  59. console.log('listening on *:3030');
  60. });