Skip to content

Commit

Permalink
restore autostart when using fire-and-forget promises. (#63)
Browse files Browse the repository at this point in the history
  • Loading branch information
mcollina authored Oct 29, 2019
1 parent df621ca commit b59fa39
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 1 deletion.
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,8 @@ Injects a fake request into an HTTP server.
- `close` - whether the request will emit a `close` event. Defaults to `undefined`, meaning no `close` event will be emitted.
- `validate` - Optional flag to validate this options object. Defaults to `true`.
- `server` - Optional http server. It is used for binding the `dispatchFunc`.
- `autoStart` - Automatically start the request as soon as the method
is called. It is only valid when not passing a callback. Defaults to `true`.
- `callback` - the callback function using the signature `function (err, res)` where:
- `err` - error object
- `res` - a response object where:
Expand Down
10 changes: 9 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,14 @@ function Chain (dispatch, option) {
this.dispatch = dispatch
this._hasInvoked = false
this._promise = null

if (this.option.autoStart !== false) {
process.nextTick(() => {
if (!this._hasInvoked) {
this.end()
}
})
}
}

const httpMethods = [
Expand Down Expand Up @@ -170,8 +178,8 @@ Object.getOwnPropertyNames(Promise.prototype).forEach(method => {
if (this._hasInvoked === true) {
throw new Error(errorMessage)
}
this._promise = doInject(this.dispatch, this.option)
this._hasInvoked = true
this._promise = doInject(this.dispatch, this.option)
}
return this._promise[method](...args)
}
Expand Down
37 changes: 37 additions & 0 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -1264,6 +1264,43 @@ test('Response.json() should throw an error if the payload is not of valid JSON
})
})

test('promise api should auto start (fire and forget)', (t) => {
t.plan(1)

function dispatch (req, res) {
t.pass('dispatch called')
res.writeHead(200, { 'Content-Type': 'text/plain' })
res.end()
}

inject(dispatch, 'http://example.com:8080/hello')
})

test('disabling autostart', (t) => {
t.plan(3)

let called = false

function dispatch (req, res) {
t.pass('dispatch called')
called = true
res.writeHead(200, { 'Content-Type': 'text/plain' })
res.end()
}

const p = inject(dispatch, {
url: 'http://example.com:8080/hello',
autoStart: false
})

setImmediate(() => {
t.equal(called, false)
p.then(() => {
t.equal(called, true)
})
})
})

function getTestStream (encoding) {
const word = 'hi'
let i = 0
Expand Down

0 comments on commit b59fa39

Please sign in to comment.