-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathfetch.js
116 lines (99 loc) · 2.87 KB
/
fetch.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
const ButterCMS = require('buttercms');
class FetchButterCMSData {
constructor({ authToken, levels, locales, pageSize, preview } = {}) {
if (!authToken) throw new Error('ButterSource: Missing API Key');
this.params = {
levels: levels || 2,
page_size: pageSize || 100,
preview: preview ? 1 : 0
};
this.locales = locales || [];
this.client = ButterCMS(authToken);
}
async getPagesWithPageType(pageType) {
if (this.locales.length) {
return (await Promise.all(
this.locales.map(locale =>
this.getLocalizedPagesWithPageType(pageType, locale)
)
)).flat();
}
return this.getLocalizedPagesWithPageType(pageType, null);
}
async getBlogPosts() {
let allPosts = [];
let page = 1;
while (page) {
const posts = await this.client.post.list({ ...this.params, page });
const {
data,
meta: { next_page: nextPage }
} = posts.data;
allPosts = allPosts.concat(data);
page = nextPage;
}
return allPosts;
}
getCollectionsData(collectionsSlugs) {
return collectionsSlugs.reduce(async (resPromise, collectionSlug) => {
const res = await resPromise;
let allItems = [];
if (this.locales.length) {
allItems = (await Promise.all(
this.locales.map(async locale => {
const items = await this.getCollectionData(collectionSlug, locale);
// each collection item should have locale
return items.map(item => ({ ...item, locale }));
})
)).flat();
} else {
allItems = await this.getCollectionData(collectionSlug, null);
}
return { ...res, [collectionSlug]: allItems };
}, Promise.resolve({}));
}
async getLocalizedPagesWithPageType(pageType, locale) {
const pagesWithPageType = [];
let page = 1;
const localLocale = locale ? { locale } : {};
while (page) {
const pages = await this.client.page.list(pageType, {
...this.params,
...localLocale,
page
});
const {
data,
meta: { next_page: nextPage }
} = pages.data;
data.forEach(item => {
pagesWithPageType.push({
...item,
...localLocale
});
});
page = nextPage;
}
return pagesWithPageType;
}
async getCollectionData(collectionSlug, locale) {
const allCollectionsData = [];
const localLocale = locale ? { locale } : {};
let page = 1;
while (page) {
const collection = await this.client.content.retrieve([collectionSlug], {
...this.params,
page,
...localLocale
});
const {
data,
meta: { next_page: nextPage }
} = collection.data;
allCollectionsData.push(...data[collectionSlug]);
page = nextPage;
}
return allCollectionsData;
}
}
module.exports = FetchButterCMSData;