-
Notifications
You must be signed in to change notification settings - Fork 10.3k
/
normalize.js
646 lines (571 loc) · 19.8 KB
/
normalize.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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
const _ = require(`lodash`)
const stringify = require(`json-stringify-safe`)
const { createContentDigest } = require(`gatsby-core-utils`)
const digest = str => createContentDigest(str)
const { getNormalizedRichTextField } = require(`./rich-text`)
const typePrefix = `Contentful`
const makeTypeName = type => _.upperFirst(_.camelCase(`${typePrefix} ${type}`))
const getLocalizedField = ({ field, locale, localesFallback }) => {
if (!_.isUndefined(field[locale.code])) {
return field[locale.code]
} else if (
!_.isUndefined(locale.code) &&
!_.isUndefined(localesFallback[locale.code])
) {
return getLocalizedField({
field,
locale: { code: localesFallback[locale.code] },
localesFallback,
})
} else {
return null
}
}
const buildFallbackChain = locales => {
const localesFallback = {}
_.each(
locales,
locale => (localesFallback[locale.code] = locale.fallbackCode)
)
return localesFallback
}
const makeGetLocalizedField = ({ locale, localesFallback }) => field =>
getLocalizedField({ field, locale, localesFallback })
exports.getLocalizedField = getLocalizedField
exports.buildFallbackChain = buildFallbackChain
// If the id starts with a number, left-pad it with a c (for Contentful of
// course :-))
const fixId = id => {
if (!_.isString(id)) {
id = id.toString()
}
if (!isNaN(id.slice(0, 1))) {
return `c${id}`
}
return id
}
exports.fixId = fixId
const shouldBeSkipped = (object, alreadyWalkedObjectRefs) =>
!object || typeof object !== `object` || alreadyWalkedObjectRefs.has(object)
// Walk the object model and find any property named `sys`. If it
// contains an `id` then make sure the id is a string and if it starts with a
// number, prefix it with (an arbitrarily chosen) `c`, for "contentful".
// The `front` tracks which objects have been visited to prevent infinite
// recursion on cyclic structures.
const fixIds = object => {
if (!object || typeof object !== `object`) return
const objectsToProcess = [object]
const alreadyWalkedObjectRefs = new Set(objectsToProcess)
while (objectsToProcess.length !== 0) {
const current = objectsToProcess.pop()
if (Array.isArray(current)) {
current.forEach(item => {
if (shouldBeSkipped(item, alreadyWalkedObjectRefs)) return
objectsToProcess.push(item)
alreadyWalkedObjectRefs.add(item)
})
continue
}
Object.keys(current).forEach(key => {
const currentProp = current[key]
if (shouldBeSkipped(currentProp, alreadyWalkedObjectRefs)) return
// The `contentful_id` is ours and we want to make sure we don't visit the
// same node twice (this is possible if the same node appears in two
// separate branches while sharing a common ancestor). This check makes
// sure we keep the original `id` preserved in `contentful_id`.
if (key === `sys` && !currentProp.contentful_id) {
currentProp.contentful_id = currentProp.id
currentProp.id = fixId(currentProp.id)
}
objectsToProcess.push(currentProp)
alreadyWalkedObjectRefs.add(currentProp)
})
}
}
exports.fixIds = fixIds
const makeId = ({ spaceId, id, currentLocale, defaultLocale }) =>
currentLocale === defaultLocale
? `${spaceId}___${id}`
: `${spaceId}___${id}___${currentLocale}`
exports.makeId = makeId
const makeMakeId = ({ currentLocale, defaultLocale, createNodeId }) => (
spaceId,
id
) => createNodeId(makeId({ spaceId, id, currentLocale, defaultLocale }))
exports.buildEntryList = ({ contentTypeItems, currentSyncData }) =>
contentTypeItems.map(contentType =>
currentSyncData.entries.filter(
entry => entry.sys.contentType.sys.id === contentType.sys.id
)
)
exports.buildResolvableSet = ({
entryList,
existingNodes = [],
assets = [],
locales,
defaultLocale,
}) => {
const resolvable = new Set()
existingNodes.forEach(n => {
if (n.contentful_id) {
// We need to add only root level resolvable (assets and entries)
// derived nodes (markdown or JSON) will be recreated if needed.
// We also need to apply `fixId` as some objects will have ids
// prefixed with `c` and fixIds will recursively apply that
// and resolvable ids need to match that.
resolvable.add(fixId(n.contentful_id))
}
})
entryList.forEach(entries => {
entries.forEach(entry => {
resolvable.add(entry.sys.id)
})
})
assets.forEach(assetItem => resolvable.add(assetItem.sys.id))
return resolvable
}
exports.buildForeignReferenceMap = ({
contentTypeItems,
entryList,
resolvable,
defaultLocale,
locales,
space,
useNameForId,
}) => {
const foreignReferenceMap = {}
contentTypeItems.forEach((contentTypeItem, i) => {
// Establish identifier for content type
// Use `name` if specified, otherwise, use internal id (usually a natural-language constant,
// but sometimes a base62 uuid generated by Contentful, hence the option)
let contentTypeItemId
if (useNameForId) {
contentTypeItemId = contentTypeItem.name.toLowerCase()
} else {
contentTypeItemId = contentTypeItem.sys.id.toLowerCase()
}
entryList[i].forEach(entryItem => {
const entryItemFields = entryItem.fields
Object.keys(entryItemFields).forEach(entryItemFieldKey => {
if (entryItemFields[entryItemFieldKey]) {
let entryItemFieldValue =
entryItemFields[entryItemFieldKey][defaultLocale]
// If this is an array of single reference object
// add to the reference map, otherwise ignore.
if (Array.isArray(entryItemFieldValue)) {
if (
entryItemFieldValue[0] &&
entryItemFieldValue[0].sys &&
entryItemFieldValue[0].sys.type &&
entryItemFieldValue[0].sys.id
) {
entryItemFieldValue.forEach(v => {
// Don't create link to an unresolvable field.
if (!resolvable.has(v.sys.id)) {
return
}
if (!foreignReferenceMap[v.sys.id]) {
foreignReferenceMap[v.sys.id] = []
}
foreignReferenceMap[v.sys.id].push({
name: `${contentTypeItemId}___NODE`,
id: entryItem.sys.id,
spaceId: space.sys.id,
})
})
}
} else if (
entryItemFieldValue &&
entryItemFieldValue.sys &&
entryItemFieldValue.sys.type &&
entryItemFieldValue.sys.id &&
resolvable.has(entryItemFieldValue.sys.id)
) {
if (!foreignReferenceMap[entryItemFieldValue.sys.id]) {
foreignReferenceMap[entryItemFieldValue.sys.id] = []
}
foreignReferenceMap[entryItemFieldValue.sys.id].push({
name: `${contentTypeItemId}___NODE`,
id: entryItem.sys.id,
spaceId: space.sys.id,
})
}
}
})
})
})
return foreignReferenceMap
}
function prepareTextNode(node, key, text, createNodeId) {
const str = _.isString(text) ? text : ``
const textNode = {
id: createNodeId(`${node.id}${key}TextNode`),
parent: node.id,
children: [],
[key]: str,
internal: {
type: _.camelCase(`${node.internal.type} ${key} TextNode`),
mediaType: `text/markdown`,
content: str,
contentDigest: digest(str),
},
}
node.children = node.children.concat([textNode.id])
return textNode
}
function prepareRichTextNode(node, key, content, createNodeId) {
const str = stringify(content)
const richTextNode = {
...content,
id: createNodeId(`${node.id}${key}RichTextNode`),
parent: node.id,
children: [],
[key]: str,
internal: {
type: _.camelCase(`${node.internal.type} ${key} RichTextNode`),
mediaType: `text/richtext`,
content: str,
contentDigest: digest(str),
},
}
node.children = node.children.concat([richTextNode.id])
return richTextNode
}
function prepareJSONNode(node, key, content, createNodeId, i = ``) {
const str = JSON.stringify(content)
const JSONNode = {
...(_.isPlainObject(content) ? { ...content } : { content: content }),
id: createNodeId(`${node.id}${key}${i}JSONNode`),
parent: node.id,
children: [],
internal: {
type: _.camelCase(`${node.internal.type} ${key} JSONNode`),
mediaType: `application/json`,
content: str,
contentDigest: digest(str),
},
}
node.children = node.children.concat([JSONNode.id])
return JSONNode
}
exports.createNodesForContentType = ({
contentTypeItem,
contentTypeItems,
restrictedNodeFields,
conflictFieldPrefix,
entries,
createNode,
createNodeId,
resolvable,
foreignReferenceMap,
defaultLocale,
locales,
space,
useNameForId,
richTextOptions,
}) => {
// Establish identifier for content type
// Use `name` if specified, otherwise, use internal id (usually a natural-language constant,
// but sometimes a base62 uuid generated by Contentful, hence the option)
let contentTypeItemId
if (useNameForId) {
contentTypeItemId = contentTypeItem.name
} else {
contentTypeItemId = contentTypeItem.sys.id
}
const createNodePromises = []
locales.forEach(locale => {
const localesFallback = buildFallbackChain(locales)
const mId = makeMakeId({
currentLocale: locale.code,
defaultLocale,
createNodeId,
})
const getField = makeGetLocalizedField({
locale,
localesFallback,
})
// Warn about any field conflicts
const conflictFields = []
contentTypeItem.fields.forEach(contentTypeItemField => {
const fieldName = contentTypeItemField.id
if (restrictedNodeFields.includes(fieldName)) {
console.log(
`Restricted field found for ContentType ${contentTypeItemId} and field ${fieldName}. Prefixing with ${conflictFieldPrefix}.`
)
conflictFields.push(fieldName)
}
})
const childrenNodes = []
// First create nodes for each of the entries of that content type
const entryNodes = entries.map(entryItem => {
// Get localized fields.
const entryItemFields = _.mapValues(entryItem.fields, (v, k) => {
const fieldProps = contentTypeItem.fields.find(field => field.id === k)
const localizedField = fieldProps.localized
? getField(v)
: v[defaultLocale]
if (
fieldProps.type === `RichText` &&
richTextOptions &&
richTextOptions.resolveFieldLocales
) {
const contentTypesById = new Map()
contentTypeItems.forEach(contentTypeItem =>
contentTypesById.set(contentTypeItem.sys.id, contentTypeItem)
)
return getNormalizedRichTextField({
field: localizedField,
fieldProps,
contentTypesById,
getField,
defaultLocale,
})
}
return localizedField
})
// Prefix any conflicting fields
// https://github.com/gatsbyjs/gatsby/pull/1084#pullrequestreview-41662888
conflictFields.forEach(conflictField => {
entryItemFields[`${conflictFieldPrefix}${conflictField}`] =
entryItemFields[conflictField]
delete entryItemFields[conflictField]
})
// Add linkages to other nodes based on foreign references
Object.keys(entryItemFields).forEach(entryItemFieldKey => {
if (entryItemFields[entryItemFieldKey]) {
const entryItemFieldValue = entryItemFields[entryItemFieldKey]
if (Array.isArray(entryItemFieldValue)) {
if (
entryItemFieldValue[0] &&
entryItemFieldValue[0].sys &&
entryItemFieldValue[0].sys.type &&
entryItemFieldValue[0].sys.id
) {
// Check if there are any values in entryItemFieldValue to prevent
// creating an empty node field in case when original key field value
// is empty due to links to missing entities
const resolvableEntryItemFieldValue = entryItemFieldValue
.filter(function (v) {
return resolvable.has(v.sys.id)
})
.map(function (v) {
return mId(space.sys.id, v.sys.id)
})
if (resolvableEntryItemFieldValue.length !== 0) {
entryItemFields[
`${entryItemFieldKey}___NODE`
] = resolvableEntryItemFieldValue
}
delete entryItemFields[entryItemFieldKey]
}
} else if (
entryItemFieldValue &&
entryItemFieldValue.sys &&
entryItemFieldValue.sys.type &&
entryItemFieldValue.sys.id
) {
if (resolvable.has(entryItemFieldValue.sys.id)) {
entryItemFields[`${entryItemFieldKey}___NODE`] = mId(
space.sys.id,
entryItemFieldValue.sys.id
)
}
delete entryItemFields[entryItemFieldKey]
}
}
})
// Add reverse linkages if there are any for this node
const foreignReferences = foreignReferenceMap[entryItem.sys.id]
if (foreignReferences) {
foreignReferences.forEach(foreignReference => {
const existingReference = entryItemFields[foreignReference.name]
if (existingReference) {
// If the existing reference is a string, we're dealing with a
// many-to-one reference which has already been recorded, so we can
// skip it. However, if it is an array, add it:
if (Array.isArray(existingReference)) {
entryItemFields[foreignReference.name].push(
mId(foreignReference.spaceId, foreignReference.id)
)
}
} else {
// If there is one foreign reference, there can be many.
// Best to be safe and put it in an array to start with.
entryItemFields[foreignReference.name] = [
mId(foreignReference.spaceId, foreignReference.id),
]
}
})
}
let entryNode = {
id: mId(space.sys.id, entryItem.sys.id),
spaceId: space.sys.id,
contentful_id: entryItem.sys.contentful_id,
createdAt: entryItem.sys.createdAt,
updatedAt: entryItem.sys.updatedAt,
parent: contentTypeItemId,
children: [],
internal: {
type: `${makeTypeName(contentTypeItemId)}`,
},
sys: {},
}
// Revision applies to entries, assets, and content types
if (entryItem.sys.revision) {
entryNode.sys.revision = entryItem.sys.revision
}
// Content type applies to entries only
if (entryItem.sys.contentType) {
entryNode.sys.contentType = entryItem.sys.contentType
}
// Use default locale field.
Object.keys(entryItemFields).forEach(entryItemFieldKey => {
// Ignore fields with "___node" as they're already handled
// and won't be a text field.
if (entryItemFieldKey.split(`___`).length > 1) {
return
}
})
// Replace text fields with text nodes so we can process their markdown
// into HTML.
Object.keys(entryItemFields).forEach(entryItemFieldKey => {
// Ignore fields with "___node" as they're already handled
// and won't be a text field.
if (entryItemFieldKey.split(`___`).length > 1) {
return
}
const fieldType = contentTypeItem.fields.find(
f =>
(restrictedNodeFields.includes(f.id)
? `${conflictFieldPrefix}${f.id}`
: f.id) === entryItemFieldKey
).type
if (fieldType === `Text`) {
const textNode = prepareTextNode(
entryNode,
entryItemFieldKey,
entryItemFields[entryItemFieldKey],
createNodeId
)
childrenNodes.push(textNode)
entryItemFields[`${entryItemFieldKey}___NODE`] = textNode.id
delete entryItemFields[entryItemFieldKey]
} else if (
fieldType === `RichText` &&
_.isPlainObject(entryItemFields[entryItemFieldKey])
) {
const richTextNode = prepareRichTextNode(
entryNode,
entryItemFieldKey,
entryItemFields[entryItemFieldKey],
createNodeId
)
childrenNodes.push(richTextNode)
entryItemFields[`${entryItemFieldKey}___NODE`] = richTextNode.id
delete entryItemFields[entryItemFieldKey]
} else if (
fieldType === `Object` &&
_.isPlainObject(entryItemFields[entryItemFieldKey])
) {
const jsonNode = prepareJSONNode(
entryNode,
entryItemFieldKey,
entryItemFields[entryItemFieldKey],
createNodeId
)
childrenNodes.push(jsonNode)
entryItemFields[`${entryItemFieldKey}___NODE`] = jsonNode.id
delete entryItemFields[entryItemFieldKey]
} else if (
fieldType === `Object` &&
_.isArray(entryItemFields[entryItemFieldKey])
) {
entryItemFields[`${entryItemFieldKey}___NODE`] = []
entryItemFields[entryItemFieldKey].forEach((obj, i) => {
const jsonNode = prepareJSONNode(
entryNode,
entryItemFieldKey,
obj,
createNodeId,
i
)
childrenNodes.push(jsonNode)
entryItemFields[`${entryItemFieldKey}___NODE`].push(jsonNode.id)
})
delete entryItemFields[entryItemFieldKey]
}
})
entryNode = { ...entryItemFields, ...entryNode, node_locale: locale.code }
// Get content digest of node.
const contentDigest = digest(stringify(entryNode))
entryNode.internal.contentDigest = contentDigest
return entryNode
})
// Create a node for each content type
const contentTypeNode = {
id: createNodeId(contentTypeItemId),
parent: null,
children: [],
name: contentTypeItem.name,
displayField: contentTypeItem.displayField,
description: contentTypeItem.description,
internal: {
type: `${makeTypeName(`ContentType`)}`,
},
}
// Get content digest of node.
const contentDigest = digest(stringify(contentTypeNode))
contentTypeNode.internal.contentDigest = contentDigest
createNodePromises.push(createNode(contentTypeNode))
entryNodes.forEach(entryNode => {
createNodePromises.push(createNode(entryNode))
})
childrenNodes.forEach(entryNode => {
createNodePromises.push(createNode(entryNode))
})
})
return createNodePromises
}
exports.createAssetNodes = ({
assetItem,
createNode,
createNodeId,
defaultLocale,
locales,
space,
}) => {
const createNodePromises = []
locales.forEach(locale => {
const localesFallback = buildFallbackChain(locales)
const mId = makeMakeId({
currentLocale: locale.code,
defaultLocale,
createNodeId,
})
const getField = makeGetLocalizedField({
locale,
localesFallback,
})
const assetNode = {
contentful_id: assetItem.sys.contentful_id,
id: mId(space.sys.id, assetItem.sys.id),
parent: null,
children: [],
file: assetItem.fields.file ? getField(assetItem.fields.file) : null,
title: assetItem.fields.title ? getField(assetItem.fields.title) : ``,
description: assetItem.fields.description
? getField(assetItem.fields.description)
: ``,
node_locale: locale.code,
internal: {
type: `${makeTypeName(`Asset`)}`,
},
}
// Get content digest of node.
const contentDigest = digest(stringify(assetNode))
assetNode.internal.contentDigest = contentDigest
createNodePromises.push(createNode(assetNode))
})
return createNodePromises
}