Skip to content

Commit e0d71b0

Browse files
committed
Document 'drain' event with idle detection example
1 parent 448d2e1 commit e0d71b0

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

Readme.md

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -247,6 +247,40 @@ cannot be re-connected by design.
247247
This logic will also be part of connection pool support once I add that to this
248248
library.
249249

250+
## Idle connections
251+
252+
Connections emit `'drain'` events after they have finished all queued queries
253+
(including query callbacks). This event could be used to detect idle
254+
connections:
255+
256+
```javascript
257+
function detectIdle(connection) {
258+
connection._idleTimeout = null;
259+
260+
function clearIdleTimeout() {
261+
if (connection.idleTimeout) {
262+
clearTimeout(connection.idleTimeout);
263+
}
264+
}
265+
266+
connection.on('drain', function() {
267+
clearIdleTimeout();
268+
connection._idleTimeout = setTimeout(60000, function() {
269+
console.error("Connection was idle for 60 seconds");
270+
// or return to a pool, etc.
271+
})
272+
})
273+
274+
var query = connection.query;
275+
connection.query = function() {
276+
clearIdleTimeout();
277+
query.apply(connection, arguments);
278+
};
279+
})
280+
281+
handleDisconnect(connection);
282+
```
283+
250284
## Escaping query values
251285

252286
In order to avoid SQL Injection attacks, you should always escape any user

0 commit comments

Comments
 (0)