-
Notifications
You must be signed in to change notification settings - Fork 8
/
utils.js
74 lines (67 loc) · 1.65 KB
/
utils.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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
const fetch = require('node-fetch')
const Bottleneck = require('bottleneck')
const querystring = require('querystring')
const { ETSY_BASE_URL, ETSY_PAGE_LIMIT } = require('./constants')
async function asyncForEach(sourceArray, callback) {
for (let i = 0; i < sourceArray.length; i = i + 1) {
await callback(sourceArray[i], i, sourceArray)
}
}
function createThrottledFetch(limiterOptions = {}) {
const defaultLimiterOptions = {
minTime: 100,
}
const limiter = new Bottleneck({
...defaultLimiterOptions,
...limiterOptions,
})
function throttledFetch(...args) {
return limiter.schedule(() => fetch(...args))
}
return throttledFetch
}
async function getListingsRecursively(
shop_id,
api_key,
etsyFetch,
queryParams = {},
offset = 0
) {
const {
shop_id: _shop_id,
page: _page,
...allowableQueryParams
} = queryParams
const definedQueryParams = {}
Object.entries(allowableQueryParams).forEach(([key, value]) => {
if (value !== undefined) {
definedQueryParams[key] = value
}
})
const queryObject = {
...definedQueryParams,
api_key: api_key,
limit: ETSY_PAGE_LIMIT,
offset,
}
const query = querystring.stringify(queryObject)
const { results } = await etsyFetch(
`${ETSY_BASE_URL}/shops/${shop_id}/listings/active?${query}`
).then(res => res.json())
let nextResults = []
if (results.length) {
nextResults = await getListingsRecursively(
shop_id,
api_key,
etsyFetch,
queryParams,
offset + ETSY_PAGE_LIMIT
)
}
return [...results, ...nextResults]
}
module.exports = {
asyncForEach,
createThrottledFetch,
getListingsRecursively,
}