How to attach to an already created server?
I have recently implemented (koa-sslify)[https://github.com/turboMaCk/koa-sslify] which requires the use of https.createServer instead of app.listen in order to pass SSL options to the server.
I can't find any example of how to attach koa-socket to the koa app when using the createServer method.
Here is the code:
let app = new Koa();
let io = new IO();
io.on('connection', (ctx) => {
store.dispatch(socketConnected(ctx));
ctx.socket.on('action', (data) => {
try {
let action = JSON.parse(data);
action.meta = action.meta || {};
action.meta.ctx = ctx;
store.dispatch(action);
} catch (err) {
log.logger.info(err);
}
});
ctx.socket.on('disconnect', () => {
store.dispatch(socketDisconnected(ctx));
});
});
let sslOptions = {
pfx: fs.readFileSync(config.pfxPath),
passphrase: config.pfxPassphrase,
};
http.createServer(app.callback()).listen(config.port);
https.createServer(sslOptions, app.callback()).listen(config.sslPort);
io.attach(app);
Looking at the source code I see that the server is assigned to a server property on the app object:
app.server = http.createServer( app.callback() )
I have tried to mimic the behavior in the attach function but with no luck.
I am using the following versions:
$ npm ls | grep koa
├─┬ [email protected]
│ ├── [email protected]
│ ├── [email protected]
├─┬ [email protected]
├─┬ [email protected]
├─┬ [email protected]
│ ├─┬ [email protected]
├── [email protected]
├─┬ [email protected]
│ └─┬ [email protected]
I was eventually able to figure this out. I basically copied the code from here in the attach function in the koa-socket source. Here is the relevant parts of my code:
let app = new Koa();
let io = new IO();
let sslOptions = {
pfx: fs.readFileSync(config.pfxPath),
passphrase: config.pfxPassphrase,
};
http.createServer(app.callback()).listen(config.port);
app.server = https.createServer(sslOptions, app.callback());
app.server.listen(config.sslPort);
app.listen = function listen() {
app.server.listen.apply( app.server, arguments );
return app.server;
};
io.attach(app);
I'm not sure the best way to handle this, but I think the attach function should be updated or at least the README.