Skip to content

Commit

Permalink
Add timeout
Browse files Browse the repository at this point in the history
  • Loading branch information
daleharvey committed Nov 22, 2014
1 parent ae84da1 commit ab495e6
Showing 1 changed file with 19 additions and 0 deletions.
19 changes: 19 additions & 0 deletions lib/routes/db.js
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,7 @@ module.exports = function(app, PouchDB) {

if (req.query.feed === 'continuous' || req.query.feed === 'longpoll') {
var heartbeatInterval;
var timeout;
var heartbeat = (typeof req.query.heartbeat === 'number')
? req.query.heartbeat : 6000;
var written = false;
Expand All @@ -96,6 +97,9 @@ module.exports = function(app, PouchDB) {
}, heartbeat);

var cleanup = function () {
if (timeout) {
clearTimeout(timeout);
}
if (heartbeatInterval) {
clearInterval(heartbeatInterval);
}
Expand All @@ -117,6 +121,17 @@ module.exports = function(app, PouchDB) {
} else { // longpoll
// first check if there are >0. if so, return them immediately
req.query.live = req.query.continuous = false;
if (req.query.timeout) {
timeout = setTimeout(function() {
written = true;
res.write(JSON.stringify({
results: [],
last_seq: req.query.since
}) + '\n');
res.end();
cleanup();
}, req.query.timeout);
}
req.db.changes(req.query).on('complete', function (complete) {
if (!complete.results) {
// canceled, ignore
Expand All @@ -128,7 +143,11 @@ module.exports = function(app, PouchDB) {
cleanup();
} else { // do the longpolling
req.query.live = req.query.continuous = true;

var changes = req.db.changes(req.query).on('change', function (change) {
if (written) {
return;
}
written = true;
res.write(JSON.stringify({
results: [change],
Expand Down

0 comments on commit ab495e6

Please sign in to comment.