Permalink
Browse files

Support adding a basic timeout to requests

- If the timeout is trigger req.abort() is called.
- Also had to add an extra listener to ensure that the standard callback
  is called even if the connection ends in an error.
  • Loading branch information...
1 parent 4d0807d commit 9d050ac60cbd0ea433cc648c48965ca58bc7b70b @ejfinneran ejfinneran committed Jan 27, 2013
Showing with 36 additions and 0 deletions.
  1. +13 −0 README.md
  2. +10 −0 src/index.coffee
  3. +13 −0 test/timeout_test.coffee
View
13 README.md
@@ -96,6 +96,19 @@ client.get(function (err, req) {
})
```
+Adding simple timeout support:
+
+ client = ScopedClient.create('http://10.255.255.1:9999');
+
+ client.timeout(100);
+
+ client.get()(function(err, resp, body) {
+ if (err) {
+ util.puts("ERROR: " + err);
+ }
+ });
+
+
## Development
Run this in the main directory to compile coffeescript to javascript as you go:
View
10 src/index.coffee
@@ -34,6 +34,10 @@ class ScopedClient
headers: headers
agent: @options.agent or false
)
+ if @options.timeout
+ req.setTimeout @options.timeout, () ->
+ req.abort()
+
if callback
req.on 'error', callback
req.write reqBody, @options.encoding if sendingData
@@ -51,6 +55,8 @@ class ScopedClient
res.on 'end', ->
callback null, res, body
+ req.on 'error', (error) ->
+ callback error, null, null
req.end()
@
@@ -117,6 +123,10 @@ class ScopedClient
@options.encoding = e
@
+ timeout: (time) ->
+ @options.timeout = time
+ @
+
auth: (user, pass) ->
if !user
@options.auth = null
View
13 test/timeout_test.coffee
@@ -0,0 +1,13 @@
+ScopedClient = require '../lib'
+http = require 'http'
+assert = require 'assert'
+called = 0
+
+client = ScopedClient.create 'http://10.255.255.1:9999'
+client.timeout 100
+
+client.get() (err, resp, body) ->
+ called++ if err
+
+process.on 'exit', ->
+ assert.equal 1, called

0 comments on commit 9d050ac

Please sign in to comment.