diff --git a/lib/handlers/on-fetch.js b/lib/handlers/on-fetch.js index 7760c626..20305911 100644 --- a/lib/handlers/on-fetch.js +++ b/lib/handlers/on-fetch.js @@ -7,6 +7,7 @@ const db = require('../db'); const tools = require('../tools'); const consts = require('../consts'); const LimitedFetch = require('../limited-fetch'); +//const util = require('util'); module.exports = (server, messageHandler, userCache) => (mailbox, options, session, callback) => { server.logger.debug( @@ -100,15 +101,6 @@ module.exports = (server, messageHandler, userCache) => (mailbox, options, sessi }; } - let queryAll = false; - if (options.messages.length !== session.selected.uidList.length) { - // do not use uid selector for 1:* - query.uid = tools.checkRangeQuery(options.messages); - } else { - // 1:* - queryAll = true; - } - let isUpdated = false; let updateEntries = []; let notifyEntries = []; @@ -142,14 +134,37 @@ module.exports = (server, messageHandler, userCache) => (mailbox, options, sessi // instead of fetching all messages at once from a large mailbox // we page it into smaller queries let processPage = () => { - if (lastUid) { - query.uid = { $gt: lastUid }; + let queryAll = false; + + let pageQuery = Object.assign({}, query); + + if (options.messages.length !== session.selected.uidList.length) { + // do not use uid selector for 1:* + pageQuery.uid = tools.checkRangeQuery(options.messages, false); + } else { + // 1:* + queryAll = true; } + if (lastUid) { + if (!pageQuery.uid) { + pageQuery.uid = { $gt: lastUid }; + } else { + pageQuery.$and = [ + { + uid: pageQuery.uid + }, + { uid: { $gt: lastUid } } + ]; + } + } + + //console.log(util.inspect(pageQuery, false, 22)); + let sort = { uid: 1 }; let cursor = db.database .collection('messages') - .find(query) + .find(pageQuery) .project(projection) .sort(sort) .limit(consts.CURSOR_MAX_PAGE_SIZE) @@ -178,7 +193,7 @@ module.exports = (server, messageHandler, userCache) => (mailbox, options, sessi '[%s] FETCHERR error=%s query=%s', session.id, err.message, - JSON.stringify(query) + JSON.stringify(pageQuery) ); return done(err); } @@ -196,7 +211,7 @@ module.exports = (server, messageHandler, userCache) => (mailbox, options, sessi '[%s] FETCHERR error=%s query=%s', session.id, err.message, - JSON.stringify(query) + JSON.stringify(pageQuery) ); return done(err); }