Skip to content

Commit

Permalink
Clean up code
Browse files Browse the repository at this point in the history
  • Loading branch information
ai committed Apr 28, 2019
1 parent 66d61c4 commit d0dedd7
Show file tree
Hide file tree
Showing 4 changed files with 74 additions and 135 deletions.
125 changes: 52 additions & 73 deletions base-server.js
Original file line number Diff line number Diff line change
@@ -1,19 +1,18 @@
let { ServerConnection, MemoryStore, Log } = require('@logux/core')
let { isAbsolute, join } = require('path')
let { readFileSync } = require('fs')
let NanoEvents = require('nanoevents')
let UrlPattern = require('url-pattern')
let WebSocket = require('ws')
let nanoid = require('nanoid')
let https = require('https')
let http = require('http')
let path = require('path')
let fs = require('fs')

let startControlServer = require('./start-control-server')
let bindBackendProxy = require('./bind-backend-proxy')
let forcePromise = require('./force-promise')
let ServerClient = require('./server-client')
let parseNodeId = require('./parse-node-id')
let promisify = require('./promisify')
let Context = require('./context')
let pkg = require('./package.json')

Expand All @@ -27,14 +26,10 @@ function isPem (content) {
}
}

function readFile (root, file) {
function readFrom (root, file) {
file = file.toString()
if (!path.isAbsolute(file)) {
file = path.join(root, file)
}
return promisify(done => {
fs.readFile(file, done)
})
if (!isAbsolute(file)) file = join(root, file)
return readFileSync(file)
}

function optionError (msg) {
Expand Down Expand Up @@ -362,83 +357,67 @@ class BaseServer {
*
* @return {Promise} When the server has been bound.
*/
listen () {
async listen () {
if (!this.authenticator) {
throw new Error('You must set authentication callback by server.auth()')
}

let promise = Promise.resolve()

if (this.options.server) {
this.ws = new WebSocket.Server({ server: this.options.server })
} else {
let before = []
if (this.options.key && !isPem(this.options.key)) {
before.push(readFile(this.options.root, this.options.key))
} else {
before.push(Promise.resolve(this.options.key))
}
if (this.options.cert && !isPem(this.options.cert)) {
before.push(readFile(this.options.root, this.options.cert))
} else {
before.push(Promise.resolve(this.options.cert))
}

promise = promise
.then(() => Promise.all(before))
.then(keys => new Promise((resolve, reject) => {
if (keys[0] && keys[0].pem) {
this.http = https.createServer({ key: keys[0].pem, cert: keys[1] })
} else if (keys[0]) {
this.http = https.createServer({ key: keys[0], cert: keys[1] })
} else {
this.http = http.createServer()
}
let key = this.options.key
let cert = this.options.cert
if (key && !isPem(key)) key = readFrom(this.options.root, key)
if (cert && !isPem(cert)) cert = readFrom(this.options.root, cert)

await new Promise((resolve, reject) => {
if (key && key.pem) {
this.http = https.createServer({ key: key.pem, cert })
} else if (key) {
this.http = https.createServer({ key, cert })
} else {
this.http = http.createServer()
}

this.ws = new WebSocket.Server({ server: this.http })
this.ws.on('error', reject)
this.ws = new WebSocket.Server({ server: this.http })
this.ws.on('error', reject)

this.http.listen(this.options.port, this.options.host, resolve)
}))
this.http.listen(this.options.port, this.options.host, resolve)
})
}

promise = promise.then(() => {
return startControlServer(this)
})
await startControlServer(this)

this.unbind.push(() => promisify(done => {
promise.then(() => {
this.ws.close()
if (this.http) {
this.http.close(done)
} else {
done()
}
})
this.unbind.push(() => new Promise(resolve => {
this.ws.on('close', resolve)
this.ws.close()
}))
if (this.http) {
this.unbind.push(() => new Promise(resolve => {
this.http.on('close', resolve)
this.http.close()
}))
}

return promise.then(() => {
this.ws.on('connection', ws => {
this.addClient(new ServerConnection(ws))
})
}).then(() => {
this.reporter('listen', {
controlPassword: this.options.controlPassword,
controlHost: this.options.controlHost,
controlPort: this.options.controlPort,
loguxServer: pkg.version,
environment: this.env,
subprotocol: this.options.subprotocol,
supports: this.options.supports,
backend: this.options.backend,
server: !!this.options.server,
nodeId: this.nodeId,
redis: this.options.redis,
notes: this.listenNotes,
cert: !!this.options.cert,
host: this.options.host,
port: this.options.port
})
this.ws.on('connection', ws => {
this.addClient(new ServerConnection(ws))
})
this.reporter('listen', {
controlPassword: this.options.controlPassword,
controlHost: this.options.controlHost,
controlPort: this.options.controlPort,
loguxServer: pkg.version,
environment: this.env,
subprotocol: this.options.subprotocol,
supports: this.options.supports,
backend: this.options.backend,
server: !!this.options.server,
nodeId: this.nodeId,
redis: this.options.redis,
notes: this.listenNotes,
cert: !!this.options.cert,
host: this.options.host,
port: this.options.port
})
}

Expand Down
11 changes: 0 additions & 11 deletions promisify.js

This file was deleted.

45 changes: 22 additions & 23 deletions test/base-server.test.js
Original file line number Diff line number Diff line change
@@ -1,21 +1,20 @@
let { MemoryStore, TestTime, Log } = require('@logux/core')
let { readFileSync } = require('fs')
let WebSocket = require('ws')
let { join } = require('path')
let delay = require('nanodelay')
let https = require('https')
let http = require('http')
let path = require('path')
let fs = require('fs')

let BaseServer = require('../base-server')
let promisify = require('../promisify')
let pkg = require('../package.json')

const DEFAULT_OPTIONS = {
subprotocol: '0.0.0',
supports: '0.x'
}
const CERT = path.join(__dirname, 'fixtures/cert.pem')
const KEY = path.join(__dirname, 'fixtures/key.pem')
const CERT = join(__dirname, 'fixtures/cert.pem')
const KEY = join(__dirname, 'fixtures/key.pem')

let lastPort = 9111
function createServer (options = { }) {
Expand Down Expand Up @@ -65,12 +64,11 @@ let originEnv = process.env.NODE_ENV

afterEach(async () => {
process.env.NODE_ENV = originEnv
await Promise.all([
app ? app.destroy() : true,
server ? promisify(done => server.close(done)) : true
])
app = undefined
server = undefined
if (app) {
await app.destroy()
app = undefined
}
if (server) server.close()
})

it('saves server options', () => {
Expand Down Expand Up @@ -172,10 +170,11 @@ it('destroys application without runned server', async () => {
})

it('throws without authenticator', () => {
expect.assertions(1)
app = new BaseServer(DEFAULT_OPTIONS)
expect(() => {
app.listen()
}).toThrowError(/authentication/)
return app.listen().catch(e => {
expect(e.message).toMatch(/authentication/)
})
})

it('sets default ports and hosts', () => {
Expand All @@ -193,20 +192,20 @@ it('uses user port', () => {

it('throws a error on key without certificate', () => {
expect(() => {
app = createServer({ key: fs.readFileSync(KEY) })
app = createServer({ key: readFileSync(KEY) })
}).toThrowError(/set `cert` option/)
})

it('throws a error on certificate without key', () => {
expect(() => {
app = createServer({ cert: fs.readFileSync(CERT) })
app = createServer({ cert: readFileSync(CERT) })
}).toThrowError(/set `key` option/)
})

it('uses HTTPS', async () => {
app = createServer({
cert: fs.readFileSync(CERT),
key: fs.readFileSync(KEY)
cert: readFileSync(CERT),
key: readFileSync(KEY)
})
await app.listen()
expect(app.http instanceof https.Server).toBeTruthy()
Expand All @@ -233,8 +232,8 @@ it('loads keys by relative path', async () => {

it('supports object in SSL key', async () => {
app = createServer({
cert: fs.readFileSync(CERT),
key: { pem: fs.readFileSync(KEY) }
cert: readFileSync(CERT),
key: { pem: readFileSync(KEY) }
})
await app.listen()
expect(app.http instanceof https.Server).toBeTruthy()
Expand Down Expand Up @@ -383,16 +382,16 @@ it('accepts custom HTTP server', async () => {
server = http.createServer()
app = createServer({ server })

await promisify(done => {
server.listen(app.options.port, done)
await new Promise(resolve => {
server.listen(app.options.port, resolve)
})
await app.listen()

let ws = new WebSocket(`ws://localhost:${ app.options.port }`)
await new Promise((resolve, reject) => {
ws.onopen = resolve
ws.onerror = reject
})

expect(Object.keys(app.connected)).toHaveLength(1)
})

Expand Down
28 changes: 0 additions & 28 deletions test/promisify.test.js

This file was deleted.

0 comments on commit d0dedd7

Please sign in to comment.