WebSocketController.js 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. const WebSocket = require ('ws');
  2. const _ = require('lodash');
  3. const log = new (require('../core/AppLogger'))().log;//singleton
  4. //const utils = require('../core/utils');
  5. const cleanPeriod = 1*60*1000;//1 минута
  6. const closeSocketOnIdle = 5*60*1000;//5 минут
  7. class WebSocketController {
  8. constructor(wss, config) {
  9. this.config = config;
  10. this.isDevelopment = (config.branch == 'development');
  11. this.wss = wss;
  12. wss.on('connection', (ws) => {
  13. ws.on('message', (message) => {
  14. this.onMessage(ws, message.toString());
  15. });
  16. ws.on('error', (err) => {
  17. log(LM_ERR, err);
  18. });
  19. });
  20. setTimeout(() => { this.periodicClean(); }, cleanPeriod);
  21. }
  22. periodicClean() {
  23. try {
  24. const now = Date.now();
  25. this.wss.clients.forEach((ws) => {
  26. if (!ws.lastActivity || now - ws.lastActivity > closeSocketOnIdle - 50) {
  27. ws.terminate();
  28. }
  29. });
  30. } finally {
  31. setTimeout(() => { this.periodicClean(); }, cleanPeriod);
  32. }
  33. }
  34. async onMessage(ws, message) {
  35. let req = {};
  36. try {
  37. if (this.isDevelopment) {
  38. log(`WebSocket-IN: ${message.substr(0, 4000)}`);
  39. }
  40. req = JSON.parse(message);
  41. ws.lastActivity = Date.now();
  42. //pong for WebSocketConnection
  43. this.send({_rok: 1}, req, ws);
  44. switch (req.action) {
  45. case 'test':
  46. await this.test(req, ws); break;
  47. case 'get-config':
  48. await this.getConfig(req, ws); break;
  49. default:
  50. throw new Error(`Action not found: ${req.action}`);
  51. }
  52. } catch (e) {
  53. this.send({error: e.message}, req, ws);
  54. }
  55. }
  56. send(res, req, ws) {
  57. if (ws.readyState == WebSocket.OPEN) {
  58. ws.lastActivity = Date.now();
  59. let r = res;
  60. if (req.requestId)
  61. r = Object.assign({requestId: req.requestId}, r);
  62. const message = JSON.stringify(r);
  63. ws.send(message);
  64. if (this.isDevelopment) {
  65. log(`WebSocket-OUT: ${message.substr(0, 4000)}`);
  66. }
  67. }
  68. }
  69. //Actions ------------------------------------------------------------------
  70. async test(req, ws) {
  71. this.send({message: `${this.config.name} project is awesome`}, req, ws);
  72. }
  73. async getConfig(req, ws) {
  74. if (Array.isArray(req.params)) {
  75. const paramsSet = new Set(req.params);
  76. this.send(_.pick(this.config, this.config.webConfigParams.filter(x => paramsSet.has(x))), req, ws);
  77. } else {
  78. throw new Error('params is not an array');
  79. }
  80. }
  81. }
  82. module.exports = WebSocketController;