-
Notifications
You must be signed in to change notification settings - Fork 37
Expand file tree
/
Copy pathfetch.js
More file actions
264 lines (229 loc) · 7.17 KB
/
fetch.js
File metadata and controls
264 lines (229 loc) · 7.17 KB
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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
import { castArray, flattenDeep } from "lodash";
import qs from "qs";
import { cleanData } from "./clean-data";
export const fetchStrapiContentTypes = async (axiosInstance) => {
const [
{
data: { data: contentTypes },
},
{
data: { data: components },
},
] = await Promise.all([
axiosInstance.get("/api/content-type-builder/content-types"),
axiosInstance.get("/api/content-type-builder/components"),
]);
return {
schemas: [...contentTypes, ...components],
contentTypes,
components,
};
};
const convertQueryParameters = (queryParameters, version = 5) => {
if (version === 4) {
return queryParameters;
}
// assume v5.
// rewrite v4 publicationState=preview to status=draft
// https://docs.strapi.io/dev-docs/migration/v4-to-v5/breaking-changes/publication-state-removed
const { publicationState, ...rest } = queryParameters;
if (publicationState !== "preview") {
return queryParameters;
}
return {
...rest,
status: "draft",
};
};
export const fetchEntity = async (
{ endpoint, queryParams, uid, pluginOptions, version = 5 },
context,
) => {
const { reporter, axiosInstance } = context;
/** @type AxiosRequestConfig */
const options = {
method: "GET",
url: endpoint,
params: convertQueryParameters(queryParams, version),
// Source: https://github.com/axios/axios/issues/5058#issuecomment-1379970592
paramsSerializer: {
serialize: (parameters) => qs.stringify(parameters, { encodeValuesOnly: true }),
},
};
try {
reporter.info(
`Starting to fetch data from Strapi - ${
options.url
} with ${options.paramsSerializer.serialize(options.params)}`,
);
// Handle internationalization
const locale = pluginOptions?.i18n?.locale;
const otherLocales = [];
if (locale) {
// Ignore queryParams locale in favor of pluginOptions
delete queryParams.locale;
if (locale === "all") {
// Get all available locales
const { data: response } = await axiosInstance({
...options,
params: {
populate: {
localizations: {
fields: ["locale"],
},
},
},
});
for (const localization of response.data.localizations) {
otherLocales.push(localization.locale);
}
} else {
// Only one locale
queryParams.locale = locale;
}
}
// Fetch default entity based on request options
const { data } = await axiosInstance(options);
// Fetch other localizations of this entry if there are any
const otherLocalizationsPromises = otherLocales.map(async (locale) => {
const { data: localizationResponse } = await axiosInstance({
...options,
params: {
...options.params,
locale,
},
});
return localizationResponse.data;
});
// Run queries in parallel
const otherLocalizationsData = await Promise.all(otherLocalizationsPromises);
return castArray([data.data, ...otherLocalizationsData]).map((entry) =>
cleanData(entry, { ...context, contentTypeUid: uid }, version),
);
} catch (error) {
if (error.response.status !== 404) {
reporter.panic(
`Failed to fetch data from Strapi ${options.url} with ${JSON.stringify(options)}`,
error,
);
}
return [];
}
};
export const fetchEntities = async (
{ endpoint, queryParams, uid, pluginOptions, version = 5 },
context,
) => {
const { reporter, axiosInstance } = context;
/** @type AxiosRequestConfig */
const options = {
method: "GET",
url: endpoint,
params: convertQueryParameters(queryParams, version),
paramsSerializer: {
serialize: (parameters) => qs.stringify(parameters, { encodeValuesOnly: true }),
},
};
// Handle internationalization
const locale = pluginOptions?.i18n?.locale;
const localesToFetch = [];
if (locale) {
delete queryParams.locale;
if (locale === "all") {
// Get all available locales from first entity
const { data: previewResponse } = await axiosInstance({
...options,
params: {
...options.params,
pagination: { pageSize: 1 },
populate: {
localizations: {
fields: ["locale"],
},
},
},
});
// Add default locale from first entry
if (previewResponse.data?.[0]) {
const firstEntry = previewResponse.data[0];
const localesSet = new Set();
// Add current entry's locale
if (firstEntry.locale) {
localesSet.add(firstEntry.locale);
}
// Add other locales from localizations array or data property
const localizations = firstEntry.localizations?.data || firstEntry.localizations || [];
for (const localization of localizations) {
const localeValue = localization.locale || localization.attributes?.locale;
if (localeValue) {
localesSet.add(localeValue);
}
}
localesToFetch.push(...localesSet);
}
} else {
// Only one locale
localesToFetch.push(locale);
}
} else {
// No locale specified, fetch default
localesToFetch.push(undefined);
}
try {
// Fetch data for each locale
const allLocalesData = [];
for (const currentLocale of localesToFetch) {
const localeOptions = {
...options,
params: {
...options.params,
...(currentLocale && { locale: currentLocale }),
},
};
const { data: response } = await axiosInstance(localeOptions);
const data = response?.data || response;
const meta = response?.meta;
const page = Number.parseInt(meta?.pagination.page || 1, 10);
const pageCount = Number.parseInt(meta?.pagination.pageCount || 1, 10);
const pagesToGet = Array.from({
length: pageCount - page,
}).map((_, index) => index + page + 1);
const fetchPagesPromises = pagesToGet.map((page) => {
return (async () => {
const fetchOptions = {
...localeOptions,
params: {
...localeOptions.params,
pagination: {
...localeOptions.params.pagination,
page,
},
},
};
reporter.info(
`Starting to fetch page ${page} from Strapi - ${
fetchOptions.url
} with ${options.paramsSerializer.serialize(fetchOptions.params)}`,
);
try {
const {
data: { data },
} = await axiosInstance(fetchOptions);
return data;
} catch (error) {
reporter.panic(`Failed to fetch data from Strapi ${fetchOptions.url}`, error);
}
})();
});
const results = await Promise.all(fetchPagesPromises);
allLocalesData.push(...data, ...flattenDeep(results));
}
const cleanedData = allLocalesData.map((entry) =>
cleanData(entry, { ...context, contentTypeUid: uid }, version),
);
return cleanedData;
} catch (error) {
reporter.panic(`Failed to fetch data from Strapi ${options.url}`, error);
return [];
}
};