<commit_before>const security = require('./security.js');
const settings = require('./settings.js');

let subscribers = [];

const THEME_INSTALLED = 'theme-installed';
const ORDER_RECEIVED = 'order-received';
const ORDER_CHANGED = 'order-changed';

const subscribe = (req, res) => {
  security.verifyToken(req.query.token, settings.jwtSecretKey).then(err => {
    if(err){
      res.status(403).end();
    } else {
      res.writeHead(200, {
        'Content-Type': 'text/event-stream',
        'Cache-Control': 'no-cache',
        'Connection': 'keep-alive',
        'X-Accel-Buffering': 'no'
      });
      subscribers.push(res);
    }
  })
}

const sendMessage = (data) => {
  const json = JSON.stringify(data);
  for(var i = 0; i < subscribers.length; i++) {
    try{
      subscribers[i].write(`data: ${json}\n\n`);
    } catch(e){
      console.log(e)
    }
  }
}

module.exports = {
  subscribe,
  sendMessage,
  THEME_INSTALLED,
  ORDER_RECEIVED,
  ORDER_CHANGED
}<commit_msg>Fixed SSE. Remove connections when they are closed.<commit_after>const security = require('./security.js');
const settings = require('./settings.js');

let subscribers = [];

const THEME_INSTALLED = 'theme-installed';
const ORDER_RECEIVED = 'order-received';
const ORDER_CHANGED = 'order-changed';

const subscribe = (req, res) => {
  security.verifyToken(req.query.token, settings.jwtSecretKey).then(err => {
    if(err){
      res.status(403).end();
    } else {
      res.writeHead(200, {
        'Content-Type': 'text/event-stream',
        'Cache-Control': 'no-cache',
        'Connection': 'keep-alive',
        'X-Accel-Buffering': 'no'
      });
      subscribers.push(res);

      req.on("close", () => {
        subscribers = subscribers.filter(item => item !== res);
      });
    }
  })
}

const sendMessage = (data) => {
  const json = JSON.stringify(data);
  for(var i = 0; i < subscribers.length; i++) {
    try{
      subscribers[i].write(`data: ${json}\n\n`);
    } catch(e){
    }
  }
}

module.exports = {
  subscribe,
  sendMessage,
  THEME_INSTALLED,
  ORDER_RECEIVED,
  ORDER_CHANGED
}
{'fraction_non_alphanumeric': 0.1739961759082218, 'fraction_numerical': 0.006692160611854685, 'mean_word_length': 3.0327552986512525, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 11, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6512456', 'n_tokens_mistral': 757, 'n_tokens_neox': 716, 'n_words': 129}