Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 23 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -226,7 +226,7 @@ const chat = new IO( 'chat' )

## API

### .attach( `Koa app` )
### .attach( `Koa app`, `Object config<optional>` )

Attaches to a koa application

Expand All @@ -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.
Expand Down
31 changes: 27 additions & 4 deletions index.js
Original file line number Diff line number Diff line change
@@ -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' )

Expand Down Expand Up @@ -95,20 +97,41 @@ module.exports = class IO {
/**
* Attach to a koa application
* @param app <Koa app> the koa app to use
* @param config <Attach 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' );
}

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
}
}
Expand Down