Skip to content

Commit

Permalink
Merge pull request #215 from fastify/double-listen
Browse files Browse the repository at this point in the history
Handle all possible cases of double listen
  • Loading branch information
mcollina committed Sep 12, 2017
2 parents 7a9dfeb + 4d6baea commit db00917
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 10 deletions.
20 changes: 18 additions & 2 deletions fastify.js
Expand Up @@ -167,13 +167,29 @@ function build (options) {
const _cb = (hasAddress) ? cb : address
fastify.ready(function (err) {
if (err) return _cb(err)
if (listening) {
return _cb(new Error('Fastify is already listening'))
}

server.on('error', wrap)
if (hasAddress) {
server.listen(port, address, _cb)
server.listen(port, address, wrap)
} else {
server.listen(port, _cb)
server.listen(port, wrap)
}
listening = true
})

function wrap (err) {
server.removeListener('error', wrap)
if (_cb) {
_cb(err)
} else {
// this will crash the process
// it will go to 'uncaughtException'
throw err
}
}
}

function startHooks (req, res, params, store) {
Expand Down
31 changes: 30 additions & 1 deletion test/listen.test.js
Expand Up @@ -2,23 +2,26 @@

const test = require('tap').test
const Fastify = require('..')
const fastify = Fastify()

test('listen accepts a port and a callback', t => {
t.plan(2)
const fastify = Fastify()
fastify.listen(0, (err) => {
fastify.server.unref()
t.error(err)
t.pass()
fastify.close()
})
})

test('listen accepts a port, address, and callback', t => {
t.plan(2)
const fastify = Fastify()
fastify.listen(0, '127.0.0.1', (err) => {
fastify.server.unref()
t.error(err)
t.pass()
fastify.close()
})
})

Expand All @@ -31,6 +34,7 @@ test('listen after Promise.resolve()', t => {
f.server.unref()
t.error(err)
t.pass()
f.close()
})
})
})
Expand All @@ -56,3 +60,28 @@ test('register after listen using Promise.resolve()', t => {
})
})
})

test('double listen errors', t => {
t.plan(2)
const fastify = Fastify()
fastify.listen(0, (err) => {
t.error(err)
fastify.listen(fastify.server.address().port, (err) => {
t.ok(err)
fastify.close()
})
})
})

test('listen twice on the same port', t => {
t.plan(2)
const fastify = Fastify()
fastify.listen(0, (err) => {
t.error(err)
const s2 = Fastify()
s2.listen(fastify.server.address().port, (err) => {
fastify.close()
t.ok(err)
})
})
})
9 changes: 2 additions & 7 deletions test/route.test.js
Expand Up @@ -76,14 +76,9 @@ fastify.listen(0, function (err) {
t.deepEqual(JSON.parse(body), { hello: 'world' })
})
})
})

test('path can be specified in place of uri', t => {
t.plan(3)

fastify.listen(0, function (err) {
if (err) t.error(err)
fastify.server.unref()
test('path can be specified in place of uri', t => {
t.plan(3)

fastify.route({
method: 'GET',
Expand Down

0 comments on commit db00917

Please sign in to comment.