From 154c0868d4c1a3ed314880011d26720e0189f3f8 Mon Sep 17 00:00:00 2001 From: "Stepan.Zharychev" Date: Fri, 4 May 2018 12:36:29 +0200 Subject: [PATCH] Added support for HTTPS and custom port on attach. --- README.md | 24 +++++++++++++++++++++++- index.js | 31 +++++++++++++++++++++++++++---- 2 files changed, 50 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 0f066ff..b96942b 100644 --- a/README.md +++ b/README.md @@ -226,7 +226,7 @@ const chat = new IO( 'chat' ) ## API -### .attach( `Koa app` ) +### .attach( `Koa app`, `Object config` ) Attaches to a koa application @@ -235,6 +235,28 @@ io.attach( app ) app.listen( process.env.PORT ) ``` +Config: +```js +{ + port: 80, // Your custom port + https: { + key: 'path_to_your_private_key.pem', + cert: 'path_to_your_certificate.pem' + } +} +``` + +Usage with config: +```js +io.attach(app, { + port: 8081, + https: { + key: '/etc/letsencrypt/domain/key.pem', + cert: '/etc/letsencrypt/domain/cert.pem' + } +}) +``` + ### .use( `Function callback` ) Applies middleware to the stack. diff --git a/index.js b/index.js index 582a6bb..4b172db 100644 --- a/index.js +++ b/index.js @@ -1,7 +1,9 @@ "use strict"; +const fs = require('fs') const http = require( 'http' ) +const https = require( 'https' ) const socketIO = require( 'socket.io' ) const compose = require( 'koa-compose' ) @@ -95,8 +97,9 @@ module.exports = class IO { /** * Attach to a koa application * @param app the koa app to use + * @param config Configuration object to be used during attaching to the app */ - attach( app ) { + attach( app, config ) { if ( app.server && app.server.constructor.name != 'Server' ) { throw new Error( 'app.server already exists but it\'s not an http server' ); @@ -104,11 +107,31 @@ module.exports = class IO { if ( !app.server ) { // Create a server if it doesn't already exists - app.server = http.createServer( app.callback() ) + if (config.https) { + if (config.https.key && config.https.cert) { + if (typeof config.https.key === 'string' && typeof config.https.cert === 'string') { + app.server = https.createServer({ + key: fs.readFileSync(config.https.key), + cert: fs.readFileSync(config.https.cert) + }, app.callback()) + } else { + throw new Error('Specified wrong type of key/cert for HTTPS. Use string type.') + } + } else { + throw new Error('Specified partial set of parameters to initialize HTTPS. Specify key and cert paths.'); + } + } else { + app.server = http.createServer(app.callback()); + } // Patch `app.listen()` to call `app.server.listen()` - app.listen = function listen(){ - app.server.listen.apply( app.server, arguments ) + app.listen = function listen(port, ...args){ + if (config.port) { + port = config.port; + } + args.unshift(port); + + app.server.listen.apply( app.server, args ); return app.server } }