title: Socket.io with RESTful API
body: <p>I'm making a RESTful API in <code>Node.js</code>, and I would like the client side apps to be updated as soon as a message is created in the database through a <code>POST</code> request. So I decided to use <code>Socket.io</code>.</p>
  
  <p>Here is my <code>server.js</code> code:</p>
  
  <pre><code>import http from "http";
  import https from "https";
  
  http.globalAgent.maxSockets = 1024;
  https.globalAgent.maxSockets = 1024;
  
  let app = require("express")();
  let server = http.Server(app);
  let io = require('./lib/sockets').listen(server)
  
  //setup Database
  let Database = require("./util/Database").init()
  
  import { version } from "../config/version.json";
  
  app.disable("x-powered-by");
  
  import bodyParser from "body-parser";
  app.use(bodyParser.json());
  app.use(bodyParser.urlencoded({ extended: true }));
  
  import routes from "./app/routes";
  routes(app);
  
  server.listen(ENV.NODE_PORT);
  
  console.log(
    "server pid %s listening on port %s in %s mode",
    process.pid,
    ENV.NODE_PORT,
    ENV.NODE_ENV
  );
  </code></pre>
  
  <p>Here is my <code>./ib/sockets</code> file:</p>
  
  <pre><code>module.exports.listen = function(app){
    let io = require('socket.io').listen(app);
  
    io.on('connection', function (socket) {
      socket.on('newMessage', function(messageData) {
        socket.emit('addMessage', messageData);
      })
    });
  
    return io
  }
  </code></pre>
  
  <p>Here is my <code>./app/routes</code> file:</p>
  
  <pre><code>module.exports = function(app) {
    //API messages
    app.post('/api/messages/', require('./api/messages/create'));
    app.get('/api/messages/', require('./api/messages/index'));
  }
  </code></pre>
  
  <p>And here is part of my <code>./app/api/messages/create</code> file:</p>
  
  <pre><code>module.exports = function(req, res) {
    let token = req.headers['bearer-authorization'];
    let tokenSecret = ENV.API_SECRET;
    let decodedToken = jwt.verify(token, tokenSecret);
    let userId = decodedToken.userId;
    let messageType = req.body.messageType;
    let messageText = req.body.messageText;
    let targetGroupIds = req.body.targetGroupIds
    let targetCommitteeIds = req.body.targetCommitteeIds
  
    let insertMessageId;
  
    createMessage(userId, messageType, messageText)
      .then(createMessageResult =&gt; {
        insertMessageId = createMessageResult.insertId;
        linkMessageToGroupsAndCommittees(insertMessageId, targetGroupIds, targetCommitteeIds);
      })
      .then(linkMessageToGroupsAndCommitteesResult =&gt; getNewMessage(insertMessageId))
      .then(formatJSON)
      .then(send.success(res))
      .catch(send.failure(res));
  };
  </code></pre>
  
  <p>Now my question is, how can I make it so that when a new message is created, I can call something like <code>socket.emit('addMessage', {messageAdded: true})</code> in my <code>./app/api/messages/create</code> file?</p>