Skip to content

Commit 27a6a10

Browse files
committed
add timeouts to rpcs
1 parent cf752ac commit 27a6a10

File tree

3 files changed

+22
-2
lines changed

3 files changed

+22
-2
lines changed

src/index.js

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,14 +52,25 @@ export default class RohrpostClient extends EventEmitter {
5252
return promise
5353
}
5454

55-
call (name, data) {
55+
call (name, data, opts) {
56+
const options = {
57+
timeout: 2000
58+
}
59+
Object.assign(options, opts)
60+
5661
const {id, promise} = this._createRequest()
5762
const payload = {
5863
type: name,
5964
id,
6065
data
6166
}
6267
this._socket.send(JSON.stringify(payload))
68+
setTimeout(() => {
69+
if (this._openRequests[id]) {
70+
const timeoutedRequest = this._popPendingRequest(id)
71+
timeoutedRequest.deferred.reject(new Error('call timed out'))
72+
}
73+
}, options.timeout)
6374
return promise
6475
}
6576

test/all.test.js

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,11 @@ describe('Rohrpost Client', () => {
6666
done()
6767
}).catch(() => { done('should not error') })
6868
})
69+
it('should handle custom call timeouts', (done) => {
70+
client.call('my-little-timeouter', {number: 4}, {timeout: 500}).then(() => {
71+
done('should not resolve')
72+
}).catch(() => { done() })
73+
})
6974
it('should detect timeouts', (done) => {
7075
client.once('closed', done)
7176
server.drop = true

test/mock-server.js

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,8 @@ const mock = {
5151
ping: mock.handlePing,
5252
subscribe: mock.handleSubscribe,
5353
unsubscribe: mock.handleUnsubscribe,
54-
'my-little-incrementer': mock.handleIncrement
54+
'my-little-incrementer': mock.handleIncrement,
55+
'my-little-timeouter': mock.handleTimeout
5556
}
5657
handlers[message.type](socket, message)
5758
},
@@ -100,6 +101,9 @@ const mock = {
100101
}
101102
socket.send(JSON.stringify(response))
102103
},
104+
handleTimeout (socket, message) {
105+
// just let it rot
106+
},
103107
checkAuth (message) {
104108
return message.auth_jwt === 'hunter2'
105109
}

0 commit comments

Comments
 (0)