forked from tableflip/smartsurvey-client
-
Notifications
You must be signed in to change notification settings - Fork 0
/
get-all.js
45 lines (35 loc) · 1.09 KB
/
get-all.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
var each = require('async-each')
function getAll (get, options, cb) {
if (!cb) {
cb = options
options = {}
}
options = options || {}
var collect = !!cb
cb = cb || function () {}
var pageSize = options.pageSize || 10
get(1, pageSize, function (err, firstResult) {
if (err) return cb(err)
if (options.onPage) options.onPage(firstResult)
var totalPages = Math.ceil(firstResult.meta.pagination.total / pageSize)
if (totalPages < 2) {
return cb(null, firstResult)
}
var pages = []
for (var i = 2; i < totalPages + 1; i++) pages.push(i)
each(pages, function (page, cb) {
get(page, pageSize, function (err, result) {
if (err) return cb(err)
if (options.onPage) options.onPage(result)
cb(null, collect ? result : null)
})
}, function (err, results) {
if (err || !collect) return cb(err)
cb(null, [firstResult].concat(results).reduce(function (result, pageResult) {
result.data = result.data.concat(pageResult.data)
return result
}, { data: [] }))
})
})
}
module.exports = getAll