-
Notifications
You must be signed in to change notification settings - Fork 39
/
gatsby-node.js
322 lines (314 loc) · 9.43 KB
/
gatsby-node.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
"use strict";
const {
createRemoteFileNode
} = require(`gatsby-source-filesystem`);
const {
addRemoteFilePolyfillInterface
} = require('gatsby-plugin-utils/polyfill-remote-file');
const get = require('lodash/get');
const probe = require('probe-image-size');
let i = 0;
exports.pluginOptionsSchema = ({
Joi
}) => {
return Joi.object({
nodeType: Joi.string().required(),
imagePath: Joi.string().required(),
name: Joi.string(),
auth: Joi.object(),
ext: Joi.string(),
prepareUrl: Joi.function(),
type: Joi.string(),
silent: Joi.boolean(),
skipUndefinedUrls: Joi.boolean()
});
};
const isImageCdnEnabled = () => {
return process.env.GATSBY_CLOUD_IMAGE_CDN === '1' || process.env.GATSBY_CLOUD_IMAGE_CDN === 'true';
};
exports.createSchemaCustomization = ({
actions,
schema
}) => {
if (isImageCdnEnabled()) {
const RemoteImageFileType = addRemoteFilePolyfillInterface(schema.buildObjectType({
name: 'RemoteImageFile',
fields: {
id: 'ID!'
},
interfaces: ['Node', 'RemoteFile'],
extensions: {
infer: true
}
}), {
schema,
actions
});
actions.createTypes([RemoteImageFileType]);
}
};
exports.onCreateNode = async ({
node,
actions,
store,
cache,
createNodeId,
createContentDigest,
reporter
}, options) => {
const {
createNode
} = actions;
const {
nodeType,
imagePath,
name = 'localImage',
auth = {},
ext = null,
prepareUrl = null,
type = 'object',
silent = false
} = options;
const createImageNodeOptions = {
store,
cache,
createNode,
createNodeId,
createContentDigest,
auth,
ext,
name,
prepareUrl
};
if (node.internal.type === nodeType) {
// Check if any part of the path indicates the node is an array and splits at those indicators
let imagePathSegments = [];
if (imagePath.includes('[].')) {
imagePathSegments = imagePath.split('[].');
}
if (imagePathSegments.length) {
const urls = await getAllFilesUrls(imagePathSegments[0], node, {
imagePathSegments,
...createImageNodeOptions
});
await createImageNodes(urls, node, createImageNodeOptions, reporter, silent);
} else if (type === 'array') {
const urls = getPaths(node, imagePath, ext);
await createImageNodes(urls, node, createImageNodeOptions, reporter, silent);
} else {
const url = getPath(node, imagePath, ext);
await createImageNode(url, node, createImageNodeOptions, reporter);
}
}
};
function getPaths(node, path, ext = null) {
const value = get(node, path);
if (value) {
return value.map(url => ext ? url + ext : url);
}
}
// Returns value from path, adding extension when supplied
function getPath(node, path, ext = null) {
const value = get(node, path);
return ext ? value + ext : value;
}
// Returns a unique cache key for a given node ID
function getCacheKeyForNodeId(nodeId) {
return `gatsby-plugin-remote-images-${nodeId}`;
}
async function createImageNodes(urls, node, options, reporter, silent) {
const {
name,
imagePathSegments,
prepareUrl,
...restOfOptions
} = options;
let fileNode;
if (!urls) {
return;
}
const fileNodes = (await Promise.all(urls.map(async (url, index) => {
if (typeof prepareUrl === 'function') {
url = prepareUrl(url);
}
if (options.skipUndefinedUrls && !url) return;
try {
fileNode = await createRemoteFileNode({
...restOfOptions,
url,
parentNodeId: node.id
});
reporter.verbose(`Created image from ${url}`);
} catch (e) {
if (!silent) {
reporter.error(`gatsby-plugin-remote-images ERROR:`, new Error(e));
}
}
return fileNode;
}))).filter(fileNode => !!fileNode);
// Store the mapping between the current node and the newly created File node
if (fileNodes.length) {
// This associates the existing node (of user-specified type) with the new
// File nodes created via createRemoteFileNode. The new File nodes will be
// resolved dynamically through the Gatsby schema customization
// createResolvers API and which File node gets resolved for each new field
// on a given node of the user-specified type is determined by the contents
// of this mapping. The keys are based on the ID of the parent node (of
// user-specified type) and the values are each a nested mapping of the new
// image File field name to the ID of the new File node.
const cacheKey = getCacheKeyForNodeId(node.id);
const existingFileNodeMap = await options.cache.get(cacheKey);
await options.cache.set(cacheKey, {
...existingFileNodeMap,
[name]: fileNodes.map(({
id
}) => id)
});
}
}
// Creates a file node and associates the parent node to its new child
async function createImageNode(url, node, options, reporter, silent) {
const {
name,
imagePathSegments,
prepareUrl,
...restOfOptions
} = options;
let fileNodeId;
let fileNode;
if (typeof prepareUrl === 'function') {
url = prepareUrl(url);
}
if (options.skipUndefinedUrls && !url) return;
try {
if (isImageCdnEnabled()) {
fileNodeId = options.createNodeId(`RemoteImageFile >>> ${node.id}`);
const metadata = await probe(url);
await options.createNode({
id: fileNodeId,
parent: node.id,
url: url,
filename: `${node.id}.${metadata.type}`,
height: metadata.height,
width: metadata.width,
mimeType: metadata.mime,
internal: {
type: 'RemoteImageFile',
contentDigest: node.internal.contentDigest
}
});
if (!silent) {
reporter.verbose(`Created RemoteImageFile node from ${url}`);
}
} else {
fileNode = await createRemoteFileNode({
...restOfOptions,
url,
parentNodeId: node.id
});
fileNodeId = fileNode.id;
if (!silent) {
reporter.verbose(`Created image from ${url}`);
}
}
} catch (e) {
if (!silent) {
reporter.error(`gatsby-plugin-remote-images ERROR:`, new Error(e));
}
++i;
fileNode = await options.createNode({
id: options.createNodeId(`${i}`),
parent: node.id,
internal: {
type: 'File',
mediaType: 'application/octet-stream',
contentDigest: options.createContentDigest(`${i}`)
}
}, {
name: 'gatsby-source-filesystem'
});
}
// Store the mapping between the current node and the newly created File node
if (fileNode || isImageCdnEnabled()) {
// This associates the existing node (of user-specified type) with the new
// File nodes created via createRemoteFileNode. The new File nodes will be
// resolved dynamically through the Gatsby schema customization
// createResolvers API and which File node gets resolved for each new field
// on a given node of the user-specified type is determined by the contents
// of this mapping. The keys are based on the ID of the parent node (of
// user-specified type) and the values are each a nested mapping of the new
// image File field name to the ID of the new File node.
const cacheKey = getCacheKeyForNodeId(node.id);
const existingFileNodeMap = await options.cache.get(cacheKey);
await options.cache.set(cacheKey, {
...existingFileNodeMap,
[name]: fileNode ? fileNode.id : fileNodeId
});
}
}
// Recursively traverses objects/arrays at each path part, and return an array of urls
async function getAllFilesUrls(path, node, options) {
if (!path || !node) {
return;
}
const {
imagePathSegments,
ext
} = options;
const pathIndex = imagePathSegments.indexOf(path),
isPathToLeafProperty = pathIndex === imagePathSegments.length - 1,
nextValue = getPath(node, path, isPathToLeafProperty ? ext : null);
// @TODO: Need logic to handle if the leaf node is an array to then shift
// to the function of createImageNodes.
return Array.isArray(nextValue) && !isPathToLeafProperty ?
// Recursively call function with next path segment for each array element
(await Promise.all(nextValue.map(item => getAllFilesUrls(imagePathSegments[pathIndex + 1], item, options)))).reduce((arr, row) => arr.concat(row), []) :
// otherwise, handle leaf node
nextValue;
}
exports.createResolvers = ({
cache,
createResolvers
}, options) => {
const {
nodeType,
imagePath,
name = 'localImage',
type = 'object'
} = options;
if (type === 'array' || imagePath.includes('[].')) {
const resolvers = {
[nodeType]: {
[name]: {
type: isImageCdnEnabled() ? '[RemoteImageFile]' : '[File]',
resolve: async (source, _, context) => {
const fileNodeMap = await cache.get(getCacheKeyForNodeId(source.id));
if (!fileNodeMap || !fileNodeMap[name]) {
return [];
}
return fileNodeMap[name].map(id => context.nodeModel.getNodeById({
id
}));
}
}
}
};
createResolvers(resolvers);
} else {
const resolvers = {
[nodeType]: {
[name]: {
type: isImageCdnEnabled() ? 'RemoteImageFile' : 'File',
resolve: async (source, _, context) => {
const fileNodeMap = await cache.get(getCacheKeyForNodeId(source.id));
if (!fileNodeMap) return null;
return context.nodeModel.getNodeById({
id: fileNodeMap[name]
});
}
}
}
};
createResolvers(resolvers);
}
};