From 034bd33cf3ed368f5d5209840a2169c577b08c9d Mon Sep 17 00:00:00 2001 From: mscdex Date: Tue, 22 Jan 2013 19:10:21 -0500 Subject: [PATCH] better fetch() argument detection --- lib/imap.js | 49 ++++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 42 insertions(+), 7 deletions(-) diff --git a/lib/imap.js b/lib/imap.js index de10c3c..99c5cd9 100644 --- a/lib/imap.js +++ b/lib/imap.js @@ -930,7 +930,8 @@ ImapConnection.prototype.fetch = function(uids, options, what, cb) { }; ImapConnection.prototype._fetch = function(which, uids, options, what, cb) { - if (uids === undefined || uids === null + if (uids === undefined + || uids === null || (Array.isArray(uids) && uids.length === 0)) throw new Error('Nothing to fetch'); @@ -939,19 +940,53 @@ ImapConnection.prototype._fetch = function(which, uids, options, what, cb) { utils.validateUIDList(uids); var toFetch = '', prefix = ' BODY[', extensions, self = this, - parse = true, headers, key, stream, + parse, headers, key, stream, fetchers = {}; - if (typeof what === 'function') { - cb = what; - what = options; - options = {}; + // argument detection! + if (cb === undefined) { + // fetch(uids, xxxx, yyyy) + if (what === undefined) { + // fetch(uids, xxxx) + if (options === undefined) { + // fetch(uids) + what = options = {}; + } else if (typeof options === 'function') { + // fetch(uids, callback) + cb = options; + what = options = {}; + } else if (options.struct !== undefined + || options.size !== undefined + || options.markSeen !== undefined) { + // fetch(uids, options) + what = {}; + } else { + // fetch(uids, what) + what = options; + options = {}; + } + } else if (typeof what === 'function') { + // fetch(uids, xxxx, callback) + cb = what; + if (options.struct !== undefined + || options.size !== undefined + || options.markSeen !== undefined) { + // fetch(uids, options, callback) + what = {}; + } else { + // fetch(uids, what, callback) + what = options; + options = {}; + } + } } + if (!Array.isArray(what)) what = [what]; for (var i = 0, wp, pprefix, len = what.length; i < len; ++i) { wp = what[i]; + parse = true; if (wp.id !== undefined && !/^(?:[\d]+[\.]{0,1})*[\d]+$/.test(''+wp.id)) throw new Error('Invalid part id: ' + wp.id); if (( (wp.headers @@ -1153,7 +1188,7 @@ ImapConnection.prototype._fetch = function(which, uids, options, what, cb) { for (f = 0, lenf = fetches.length; f < lenf; ++f) fetches[f].emit('end'); } - cb(err); + cb&&cb(err); }); this._state.requests[this._state.requests.length - 1].fetchers = fetchers;