-
Notifications
You must be signed in to change notification settings - Fork 9
/
helpers.js
322 lines (286 loc) · 9.73 KB
/
helpers.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
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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
const { print } = require("graphql");
const { createRemoteFileNode } = require(`gatsby-source-filesystem`);
const commonmark = require('commonmark');
const path = require('path');
const reader = new commonmark.Parser();
const excludedTypes = ['GenericMorph'];
function extractExtensionFromUrl(urlString) {
const isRelativeUrl = urlString.startsWith('/');
if (isRelativeUrl) {
// For relative URLs, directly use path module to extract the extension
const extension = path.extname(urlString);
return extension ? extension.slice(1) : null; // Remove the leading dot from the extension
}
try {
const parsedUrl = new URL(urlString);
// Check if the URL has a pathname (contains a file path)
if (!parsedUrl.pathname) {
return null; // If there's no pathname, there's no extension
}
// Use path module to extract the extension
const extension = path.extname(parsedUrl.pathname);
return extension ? extension.slice(1) : null; // Remove the leading dot from the extension
} catch (error) {
// Handle invalid URL by returning null
return null;
}
}
const catchErrors = (err, operation, reporter) => {
if (err?.networkError?.result?.errors) {
err.networkError.result.errors.forEach(error => {
reportOperationError(reporter, operation, error);
});
} else if (err?.graphQLErrors) {
err.graphQLErrors.forEach(error => {
reportOperationError(reporter, operation, error);
});
} else {
reportOperationError(reporter, operation, err);
}
};
const filterExcludedTypes = node => {
const type = getTypeName(node.type);
return !excludedTypes.includes(type);
};
const formatCollectionName = name => {
return name
?.replace(/([a-z])([A-Z])/, '$1 $2')
?.replace(/\w+/g, w => w[0].toUpperCase() + w.slice(1).toLowerCase())
?.replace(/\W+/g, '');
}
const getFieldType = (type, strapi = false) => {
if (type.name === 'DateTime') {
return 'Date';
}
if (type.name === 'Long') {
return 'Float';
}
switch (type.kind) {
case 'ENUM':
return 'String';
case 'LIST':
return `[${getFieldType(type.ofType)}]`;
case 'NON_NULL':
return `${getFieldType(type.ofType)}!`;
case 'OBJECT':
case 'UNION':
return `Strapi${type.name}`;
default:
return type.name;
}
}
const getTypeName = type => {
if (type.name === 'DateTime') {
return 'Date';
}
if (type.name === 'Long') {
return 'Float';
}
switch (type.kind) {
case 'ENUM':
return 'String';
case 'LIST':
return getTypeName(type.ofType);
case 'NON_NULL':
return getTypeName(type.ofType);
default:
return type.name;
}
}
const getTypeKind = type => {
switch (type.kind) {
case 'NON_NULL':
return getTypeKind(type.ofType);
default:
return type.kind;
}
}
const getEntityType = name =>
name.match(/(.*)(?:EntityResponse|EntityResponseCollection|RelationResponseCollection)$/)?.[1];
const isListType = name => {
return /(?:EntityResponseCollection|RelationResponseCollection)$/.test(name);
};
const getEntityResponse = name =>
name.match(/(.*)(?:EntityResponse)$/)?.[1];
const getEntityResponseCollection = name =>
name.match(/(.*)(?:EntityResponseCollection)$/)?.[1];
const getCollectionType = name =>
name.match(/(.*)(?:EntityResponse|RelationResponseCollection)$/)?.[1];
const getSingleTypes = ({ singleTypes }) =>
[...singleTypes || []].map(formatCollectionName).filter(Boolean);
const getCollectionTypes = ({ collectionTypes }) =>
['UploadFile', ...collectionTypes || []].map(formatCollectionName).filter(Boolean);
const getEntityTypes = ({ collectionTypes, singleTypes }) =>
['UploadFile', ...collectionTypes || [], ...singleTypes || []].map(formatCollectionName).filter(Boolean);
const getTypeMap = collectionTypes =>
(collectionTypes || []).reduce((ac, a) => ({ ...ac, [a]: true }), {});
const reportOperationError = (reporter, operation, error) => {
const { operationName, field, collectionType, query, variables } = operation;
const extra = `
===== QUERY =====
${print(query)}
===== VARIABLES =====
${JSON.stringify(variables, null, 2)}
===== ERROR =====
`;
reporter.error(`${operationName} failed – ${error.message}\n${extra}`, error);
};
const extractFiles = (text, apiURL) => {
const files = [];
if (!text) {
return files;
}
// parse the markdown / richtext content
const parsed = reader.parse(text)
const walker = parsed.walker()
let event, node
while ((event = walker.next())) {
node = event.node
// process image nodes
if (event.entering && node.type === 'image') {
if (/^\//.test(node.destination)) {
files.push(`${apiURL}${node.destination}`);
} else if (/^http/i.test(node.destination)) {
files.push(node.destination);
}
} else if (event.entering && node.type === 'html_block' && node.literal) {
let match
const regex = /<img[^>]+src="?([^"\s]+)"?\s*/gi
while (match = regex.exec(node.literal)) {
if (/^\//.test(match[1])) {
files.push(`${apiURL}${match[1]}`);
} else if (/^http/i.test(match[1])) {
files.push(match[1]);
}
}
}
}
return files.filter(Boolean);
};
const shouldDownloadFile = (pluginOptions, url) => {
const ext = extractExtensionFromUrl(url);
// Defaulting to all files
return [true, null, undefined].includes(pluginOptions?.download) || pluginOptions?.download?.includes?.(ext);
}
const processFieldData = async (data, options) => {
const { pluginOptions, nodeId, createNode, createNodeId, getCache, uploadFileMap } = options || {};
const apiURL = pluginOptions?.apiURL;
const inlineImages = pluginOptions?.inlineImages?.typesToParse;
const __typename = data?.__typename;
const output = JSON.parse(JSON.stringify(data));
// Extract files and download.
if (__typename === 'UploadFile' && data.url) {
if (shouldDownloadFile(pluginOptions, data.url)) {
const url = /^\//.test(data.url) ? `${apiURL}${data.url}` : data.url;
const fileNode = await createRemoteFileNode({
url,
parentNodeId: nodeId,
createNode,
createNodeId,
getCache,
httpHeaders: pluginOptions.headers || {},
});
if (fileNode) {
output.file = fileNode.id;
}
}
}
// Extract markdown / richtext files and download.
if (inlineImages?.[__typename]) {
await Promise.all((inlineImages[__typename] || []).map(async field => {
const files = extractFiles(data[field], apiURL);
if (files?.length) {
await Promise.all(files.map(async (uri, index) => {
const url = uri.replace(apiURL, '').split('#')[0].split('?')[0]; // lookup can only find file nodes without applied styles (#xxx).
const nodeId = uploadFileMap[url];
let file;
if (!nodeId) {
if (shouldDownloadFile(pluginOptions, uri)) {
const fileNode = await createRemoteFileNode({
url: uri,
parentNodeId: nodeId,
createNode,
createNodeId,
getCache,
httpHeaders: pluginOptions.headers || {},
});
if (fileNode) {
file = fileNode.id;
}
}
}
if (!output?.[`${field}_images`]) {
output[`${field}_images`] = [];
}
output[`${field}_images`][index] = { uri, url, nodeId, ...file && { file } };
}));
}
}));
}
await Promise.all(Object.keys(data).map(async key => {
const value = data?.[key];
if (value?.__typename) {
const entityType = getEntityType(value.__typename);
if (entityType && value?.data) {
if (value.data.length) {
output[key].nodeIds = value.data.map(item => createNodeId(`Strapi${entityType}-${item.id}`));
} else if (value.data.id) {
output[key].nodeId = createNodeId(`Strapi${entityType}-${value.data.id}`);
} else {
output[key] = null;
}
} else {
output[key] = await processFieldData(value, options);
}
} else if (value instanceof Array) {
output[key] = await Promise.all(value.map(item => processFieldData(item, options)));
}
}));
return output;
}
let warnOnceForNoSupport = false
const createNodeManifest = (uid, id, node, unstable_createNodeManifest) => {
// This env variable is provided automatically on Gatsby Cloud hosting
const isPreview = process.env.GATSBY_IS_PREVIEW === 'true';
const createNodeManifestIsSupported =
typeof unstable_createNodeManifest === 'function';
const shouldCreateNodeManifest = isPreview && createNodeManifestIsSupported;
if (shouldCreateNodeManifest) {
if (uid && id && node?.updatedAt) {
const updatedAt = node.updatedAt;
const manifestId = `${uid}-${id}-${updatedAt}`;
unstable_createNodeManifest({
manifestId,
node,
updatedAtUTC: updatedAt,
});
}
} else if (
// it's helpful to let users know if they're using an outdated Gatsby version so they'll upgrade for the best experience
isPreview && !createNodeManifestIsSupported && !warnOnceForNoSupport
) {
console.warn(
`${sourcePluginName}: Your version of Gatsby core doesn't support Content Sync (via the unstable_createNodeManifest action). Please upgrade to the latest version to use Content Sync in your site.`
)
// This is getting called for every entry node so we don't want the console logs to get cluttered
warnOnceForNoSupport = true
}
}
module.exports = {
catchErrors,
createNodeManifest,
filterExcludedTypes,
getEntityResponse,
getEntityResponseCollection,
getEntityType,
getEntityTypes,
getCollectionType,
getCollectionTypes,
getSingleTypes,
getTypeKind,
getTypeMap,
getTypeName,
getFieldType,
isListType,
processFieldData,
};