-
Notifications
You must be signed in to change notification settings - Fork 10.3k
/
normalize.js
381 lines (336 loc) · 11.4 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
const _ = require(`lodash`)
const crypto = require(`crypto`)
const stringify = require(`json-stringify-safe`)
const deepMap = require(`deep-map`)
const digest = str =>
crypto
.createHash(`md5`)
.update(str)
.digest(`hex`)
const typePrefix = `Contentful`
const makeTypeName = type => _.upperFirst(_.camelCase(`${typePrefix} ${type}`))
const getLocalizedField = ({ field, defaultLocale, locale }) => {
if (field[locale.code]) {
return field[locale.code]
} else if (field[locale.fallbackCode]) {
return field[locale.fallbackCode]
} else {
return null
}
}
const makeGetLocalizedField = ({ locale, defaultLocale }) => field =>
getLocalizedField({ field, locale, defaultLocale })
exports.getLocalizedField = getLocalizedField
// 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
exports.fixIds = object =>
deepMap(object, (v, k) => (k === `id` ? fixId(v) : v))
const makeId = ({ id, currentLocale, defaultLocale }) =>
currentLocale === defaultLocale ? id : `${id}___${currentLocale}`
exports.makeId = makeId
const makeMakeId = ({ currentLocale, defaultLocale }) => id =>
makeId({ 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 => resolvable.add(n.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,
}) => {
const foreignReferenceMap = {}
contentTypeItems.forEach((contentTypeItem, i) => {
const contentTypeItemId = contentTypeItem.name.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,
})
})
}
} 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,
})
}
}
})
})
})
return foreignReferenceMap
}
function createTextNode(node, key, text, createNode) {
const str = _.isString(text) ? text : ` `
const textNode = {
id: `${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])
createNode(textNode)
return textNode.id
}
exports.createTextNode = createTextNode
exports.createContentTypeNodes = ({
contentTypeItem,
restrictedNodeFields,
conflictFieldPrefix,
entries,
createNode,
resolvable,
foreignReferenceMap,
defaultLocale,
locales,
}) => {
const contentTypeItemId = contentTypeItem.name
locales.forEach(locale => {
const mId = makeMakeId({ currentLocale: locale.code, defaultLocale })
const getField = makeGetLocalizedField({ locale, defaultLocale })
// 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)
}
})
// 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 => getField(v))
// 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].sys &&
entryItemFieldValue[0].sys.type &&
entryItemFieldValue[0].sys.id
) {
entryItemFields[
`${entryItemFieldKey}___NODE`
] = entryItemFieldValue
.filter(v => resolvable.has(v.sys.id))
.map(v => mId(v.sys.id))
delete entryItemFields[entryItemFieldKey]
}
} else if (
entryItemFieldValue &&
entryItemFieldValue.sys &&
entryItemFieldValue.sys.type &&
entryItemFieldValue.sys.id &&
resolvable.has(entryItemFieldValue.sys.id)
) {
entryItemFields[`${entryItemFieldKey}___NODE`] = mId(
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) {
entryItemFields[foreignReference.name].push(
mId(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.id)]
}
})
}
let entryNode = {
id: mId(entryItem.sys.id),
createdAt: entryItem.sys.createdAt,
updatedAt: entryItem.sys.updatedAt,
parent: contentTypeItemId,
children: [],
internal: {
type: `${makeTypeName(contentTypeItemId)}`,
},
}
// 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
}
entryItemFields[entryItemFieldKey] = entryItemFields[entryItemFieldKey]
})
// 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`) {
entryItemFields[`${entryItemFieldKey}___NODE`] = createTextNode(
entryNode,
entryItemFieldKey,
entryItemFields[entryItemFieldKey],
createNode
)
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: 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
createNode(contentTypeNode)
entryNodes.forEach(entryNode => {
createNode(entryNode)
})
})
}
exports.createAssetNodes = ({
assetItem,
createNode,
defaultLocale,
locales,
}) => {
locales.forEach(locale => {
const mId = makeMakeId({ currentLocale: locale.code, defaultLocale })
const getField = makeGetLocalizedField({ locale, defaultLocale })
const localizedAsset = { ...assetItem }
// Create a node for each asset. They may be referenced by Entries
//
// Get localized fields.
localizedAsset.fields = {
file: getField(localizedAsset.fields.file),
title: localizedAsset.fields.title
? getField(localizedAsset.fields.title)
: ``,
description: localizedAsset.fields.description
? getField(localizedAsset.fields.description)
: ``,
}
const assetNode = {
id: mId(localizedAsset.sys.id),
parent: null,
children: [],
...localizedAsset.fields,
node_locale: locale.code,
internal: {
type: `${makeTypeName(`Asset`)}`,
},
}
// Get content digest of node.
const contentDigest = digest(stringify(assetNode))
assetNode.internal.contentDigest = contentDigest
createNode(assetNode)
})
}