-
Notifications
You must be signed in to change notification settings - Fork 10.3k
/
normalize.js
408 lines (363 loc) · 10.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
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
const crypto = require(`crypto`)
const deepMapKeys = require(`deep-map-keys`)
const _ = require(`lodash`)
const uuidv5 = require(`uuid/v5`)
const { createRemoteFileNode } = require(`gatsby-source-filesystem`)
const colorized = require(`./output-color`)
const conflictFieldPrefix = `wordpress_`
// restrictedNodeFields from here https://www.gatsbyjs.org/docs/node-interface/
const restrictedNodeFields = [`id`, `children`, `parent`, `fields`, `internal`]
/**
* Encrypts a String using md5 hash of hexadecimal digest.
*
* @param {any} str
*/
const digest = str =>
crypto
.createHash(`md5`)
.update(str)
.digest(`hex`)
/**
* Validate the GraphQL naming convetions & protect specific fields.
*
* @param {any} key
* @returns the valid name
*/
function getValidKey({ key, verbose = false }) {
let nkey = String(key)
const NAME_RX = /^[_a-zA-Z][_a-zA-Z0-9]*$/
let changed = false
// Replace invalid characters
if (!NAME_RX.test(nkey)) {
changed = true
nkey = nkey.replace(/-|__|:|\.|\s/g, `_`)
}
// Prefix if first character isn't a letter.
if (!NAME_RX.test(nkey.slice(0, 1))) {
changed = true
nkey = `${conflictFieldPrefix}${nkey}`
}
if (restrictedNodeFields.includes(nkey)) {
changed = true
nkey = `${conflictFieldPrefix}${nkey}`.replace(/-|__|:|\.|\s/g, `_`)
}
if (changed && verbose)
console.log(
colorized.out(
`Object with key "${key}" breaks GraphQL naming convention. Renamed to "${nkey}"`,
colorized.color.Font.FgRed
)
)
return nkey
}
exports.getValidKey = getValidKey
// Remove the ACF key from the response when it's not an object
const normalizeACF = entities =>
entities.map(e => {
if (!_.isObject(e[`acf`])) {
delete e[`acf`]
}
return e
})
exports.normalizeACF = normalizeACF
// Create entities from the few the WordPress API returns as an object for presumably
// legacy reasons.
const normalizeEntities = entities => {
const mapType = e =>
Object.keys(e)
.filter(key => key !== `__type`)
.map(key => {
return {
id: key,
...e[key],
__type: e.__type,
}
})
return entities.reduce((acc, e) => {
switch (e.__type) {
case `wordpress__wp_types`:
return acc.concat(mapType(e))
case `wordpress__wp_api_menus_menu_locations`:
return acc.concat(mapType(e))
case `wordpress__wp_statuses`:
return acc.concat(mapType(e))
case `wordpress__wp_taxonomies`:
return acc.concat(mapType(e))
case `wordpress__acf_options`:
return acc.concat(mapType(e))
default:
return acc.concat(e)
}
}, [])
}
exports.normalizeEntities = normalizeEntities
// Standardize ids + make sure keys are valid.
exports.standardizeKeys = entities =>
entities.map(e =>
deepMapKeys(
e,
key => (key === `ID` ? getValidKey({ key: `id` }) : getValidKey({ key }))
)
)
// Standardize dates on ISO 8601 version.
exports.standardizeDates = entities =>
entities.map(e => {
Object.keys(e).forEach(key => {
if (e[`${key}_gmt`]) {
e[key] = new Date(e[`${key}_gmt`] + `z`).toJSON()
delete e[`${key}_gmt`]
}
})
return e
})
// Lift "rendered" fields to top-level
exports.liftRenderedField = entities =>
entities.map(e => {
Object.keys(e).forEach(key => {
const value = e[key]
if (_.isObject(value) && _.isString(value.rendered)) {
e[key] = value.rendered
}
})
return e
})
// Exclude entities of unknown shape
exports.excludeUnknownEntities = entities =>
entities.filter(e => e.wordpress_id) // Excluding entities without ID
const seedConstant = `b2012db8-fafc-5a03-915f-e6016ff32086`
const typeNamespaces = {}
exports.createGatsbyIds = entities =>
entities.map(e => {
let namespace
if (typeNamespaces[e.__type]) {
namespace = typeNamespaces[e.__type]
} else {
typeNamespaces[e.__type] = uuidv5(e.__type, seedConstant)
namespace = typeNamespaces[e.__type]
}
e.id = uuidv5(e.wordpress_id.toString(), namespace)
return e
})
// Build foreign reference map.
exports.mapTypes = entities => {
const groups = _.groupBy(entities, e => e.__type)
for (let groupId in groups) {
groups[groupId] = groups[groupId].map(e => {
return {
wordpress_id: e.wordpress_id,
id: e.id,
}
})
}
return groups
}
exports.mapAuthorsToUsers = entities => {
const users = entities.filter(e => e.__type === `wordpress__wp_users`)
return entities.map(e => {
if (e.author) {
// Find the user
const user = users.find(u => u.wordpress_id === e.author)
if (user) {
e.author___NODE = user.id
// Add a link to the user to the entity.
if (!user.all_authored_entities___NODE) {
user.all_authored_entities___NODE = []
}
user.all_authored_entities___NODE.push(e.id)
if (!user[`authored_${e.__type}___NODE`]) {
user[`authored_${e.__type}___NODE`] = []
}
user[`authored_${e.__type}___NODE`].push(e.id)
delete e.author
}
}
return e
})
}
exports.mapPostsToTagsCategories = entities => {
const tags = entities.filter(e => e.__type === `wordpress__TAG`)
const categories = entities.filter(e => e.__type === `wordpress__CATEGORY`)
return entities.map(e => {
if (e.__type === `wordpress__POST`) {
// Replace tags & categories with links to their nodes.
if (e.tags.length) {
e.tags___NODE = e.tags.map(
t => tags.find(tObj => t === tObj.wordpress_id).id
)
delete e.tags
}
if (e.categories.length) {
e.categories___NODE = e.categories.map(
c => categories.find(cObj => c === cObj.wordpress_id).id
)
delete e.categories
}
}
return e
})
}
// TODO generalize this for all taxonomy types.
exports.mapTagsCategoriesToTaxonomies = entities =>
entities.map(e => {
// Where should api_menus stuff link to?
if (e.taxonomy && e.__type !== `wordpress__wp_api_menus_menus`) {
// Replace taxonomy with a link to the taxonomy node.
e.taxonomy___NODE = entities.find(t => t.wordpress_id === e.taxonomy).id
delete e.taxonomy
}
return e
})
exports.mapEntitiesToMedia = entities => {
const media = entities.filter(e => e.__type === `wordpress__wp_media`)
return entities.map(e => {
// Map featured_media to its media node
let featuredMedia
if (e.featured_media) {
featuredMedia = media.find(m => m.wordpress_id === e.featured_media)
}
if (featuredMedia) {
e.featured_media___NODE = featuredMedia.id
}
// Always delete even if we can't find a featuredMedia as WordPress' API sets
// featured_media to 0 when there isn't one which is useless to us.
delete e.featured_media
const isPhoto = field =>
_.isObject(field) &&
field.wordpress_id &&
field.url &&
field.width &&
field.height
? true
: false
const photoRegex = /\.(gif|jpg|jpeg|tiff|png)$/i
const isPhotoUrl = filename => photoRegex.test(filename)
const replacePhoto = field =>
media.find(m => m.wordpress_id === field.wordpress_id).id
const replaceFieldsInObject = object => {
_.each(object, (value, key) => {
if (_.isArray(value)) {
value.forEach(v => replaceFieldsInObject(v))
}
if (isPhoto(value)) {
object[`${key}___NODE`] = replacePhoto(value)
delete object[key]
}
})
}
if (e.acf) {
_.each(e.acf, (value, key) => {
if (_.isString(value) && isPhotoUrl(value)) {
const me = media.find(m => m.source_url === value)
e.acf[`${key}___NODE`] = me.id
delete e.acf[key]
}
if (_.isArray(value) && value[0].acf_fc_layout) {
e.acf[key] = e.acf[key].map(f => {
replaceFieldsInObject(f)
return f
})
}
})
}
return e
})
}
// Downloads media files and removes "sizes" data as useless in Gatsby context.
exports.downloadMediaFiles = async ({ entities, store, cache, createNode }) =>
Promise.all(
entities.map(async e => {
let fileNode
if (e.__type === `wordpress__wp_media`) {
try {
fileNode = await createRemoteFileNode({
url: e.source_url,
store,
cache,
createNode,
})
} catch (e) {
// Ignore
}
}
if (fileNode) {
e.localFile___NODE = fileNode.id
delete e.media_details.sizes
}
return e
})
)
const createACFChildNodes = (
obj,
entityId,
topLevelIndex,
type,
children,
createNode
) => {
// Replace any child arrays with pointers to nodes
_.each(obj, (value, key) => {
if (_.isArray(value) && value[0].acf_fc_layout) {
obj[`${key}___NODE`] = value.map(
v =>
createACFChildNodes(
v,
entityId,
topLevelIndex,
type + key,
children,
createNode
).id
)
delete obj[key]
}
})
const acfChildNode = {
...obj,
id: entityId + topLevelIndex + type,
parent: entityId,
children: [],
internal: { type, contentDigest: digest(JSON.stringify(obj)) },
}
createNode(acfChildNode)
children.push(acfChildNode.id)
return acfChildNode
}
exports.createNodesFromEntities = ({ entities, createNode }) => {
entities.forEach(e => {
// Create subnodes for ACF Flexible layouts
let { __type, ...entity } = e // eslint-disable-line no-unused-vars
let children = []
if (entity.acf) {
_.each(entity.acf, (value, key) => {
if (_.isArray(value) && value[0].acf_fc_layout) {
entity.acf[`${key}_${entity.type}___NODE`] = entity.acf[
key
].map((f, i) => {
const type = `WordPressAcf_${f.acf_fc_layout}`
delete f.acf_fc_layout
const acfChildNode = createACFChildNodes(
f,
entity.id + i,
key,
type,
children,
createNode
)
return acfChildNode.id
})
delete entity.acf[key]
}
})
}
let node = {
...entity,
children,
parent: null,
internal: {
type: e.__type,
contentDigest: digest(JSON.stringify(entity)),
},
}
createNode(node)
})
}