Im trying to implement Socket.io on Apostrophe cms 2.x
I don't know how to get server object from express apos
If I do the following I will have to create a new server on new port and I need socket on same ports as express app
lib/modules/apostrophe-socket/index.js
module.exports = {
construct: function(self, options) {
var server = require('http').Server(self.apos.app);
var io = require('socket.io')(server);
io.of('/api/v1/io/notifications').on('connection', function (socket) {
console.log("New connection", socket.id);
socket.on('notification', function (data) {
console.log("this is a notification ",data);
});
});
}
};
Take a look at the apostrophe-express module which sets up the express app. The server object is reachable as apos.modules['apostrophe-express'].server. That is established quite late in the startup process, because once it's there connections can start coming in. One good time to access it would be in an afterListen: function(err) { ... } callback right in app.js. Note that if err is present then it didn't listen successfully and since you provided an afterListen function, you're responsible for exiting.
So your code could look like:
// in app.js
afterListen: function(err) {
if (err) {
console.error(err);
process.exit(1);
}
var io = require('socket.io')(apos.modules['apostrophe-express'].server);
}
It is problematic that we don't emit a promise event for afterListen
, so you're stuck doing this with a callback in app.js
rather than adding an event listener in your own module, which would structure your code better. You could however call a method in one of your own modules from afterListen
. We'll look at adding a promise event at this point in initialization.