-
Notifications
You must be signed in to change notification settings - Fork 9
/
migration.js
627 lines (542 loc) · 15.5 KB
/
migration.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
const contentful = require('contentful-management')
const axios = require('axios')
const fs = require('fs');
const TurndownService = require('turndown')
/**
* Global variables that we're going use throughout this script
* -----------------------------------------------------------------------------
*/
/**
* Main WordPress endpoint.
*/
const wpEndpoint = `https://mywebsite.com/wp-json/wp/v2/`
/**
* API Endpoints that we'd like to receive data from
* (e.g. /wp-json/wp/v2/${key})
*/
let wpData = {
'posts': [],
'tags': [],
'categories': [],
'media': []
};
/**
* Contentful API requirements
*/
const ctfData = {
accessToken: '[ACCESS_TOKEN]',
environment: '[ENVIRONMENT_ID]',
spaceId: '[SPACE_ID]'
}
Object.freeze(ctfData);
/**
* Creation of Contentful Client
*/
const ctfClient = contentful.createClient({
accessToken: ctfData.accessToken
})
/**
* Internal: log output separator for terminal.
*/
const logSeparator = `-------`
/**
* Object to store WordPress API data in
*/
let apiData = {}
/**
* Object to store Contentful Data in.
*/
let contentfulData = []
/**
* Markdown / Content conversion functions.
*/
const turndownService = new TurndownService({
codeBlockStyle: 'fenced'
})
/**
* Convert HTML codeblocks to Markdown codeblocks.
*/
turndownService.addRule('fencedCodeBlock', {
filter: function (node, options) {
return (
options.codeBlockStyle === 'fenced' &&
node.nodeName === 'PRE' &&
node.firstChild &&
node.firstChild.nodeName === 'CODE'
)
},
replacement: function (content, node, options) {
let className = node.firstChild.getAttribute('class') || ''
let language = (className.match(/language-(\S+)/) || [null, ''])[1]
return (
'\n\n' + options.fence + language + '\n' +
node.firstChild.textContent +
'\n' + options.fence + '\n\n'
)
}
})
/**
* Convert inline HTML images to inline markdown image format.
*/
turndownService.addRule('replaceWordPressImages', {
filter: ['img'],
replacement: function(content, node, options) {
let assetUrl = contentfulData.assets.filter(asset => {
let assertFileName = asset.split('/').pop()
let nodeFileName = node.getAttribute('src').split('/').pop()
if (assertFileName === nodeFileName) {
return asset
}
})[0];
return `![${node.getAttribute('alt')}](${assetUrl})`
}
})
/**
* Main Migration Script.
* -----------------------------------------------------------------------------
*/
function migrateContent() {
let promises = [];
console.log(logSeparator)
console.log(`Getting WordPress API data`)
console.log(logSeparator)
// Loop over our content types and create API endpoint URLs
for (const [key, value] of Object.entries(wpData)) {
let wpUrl = `${wpEndpoint}${key}?per_page=90`
promises.push(wpUrl)
}
// console.log(promises)
getAllData(promises)
.then(response =>{
apiData = response
mapData();
}).catch(error => {
console.log(error)
})
}
function getAllData(URLs){
return Promise.all(URLs.map(fetchData));
}
function fetchData(URL) {
return axios
.get(URL)
.then(function(response) {
return {
success: true,
endpoint: '',
data: response.data
};
})
.catch(function(error) {
return { success: false };
});
}
/**
* Get our entire API response and filter it down to only show content that we want to include
*/
function mapData() {
// Get WP posts from API object
// Loop over our conjoined data structure and append data types to each child.
for (const [index, [key, value]] of Object.entries(Object.entries(wpData))) {
apiData[index].endpoint = key
}
console.log(`Reducing API data to only include fields we want`)
let apiPosts = getApiDataType('posts')[0];
// Loop over posts - note: we probably /should/ be using .map() here.
for (let [key, postData] of Object.entries(apiPosts.data)) {
console.log(`Parsing ${postData.slug}`)
/**
* Create base object with only limited keys
* (e.g. just 'slug', 'categories', 'title') etc.
*
* The idea here is that the key will be your Contentful field name
* and the value be the WP post value. We will later match the keys
* used here to their Contentful fields in the API.
*/
let fieldData = {
id: postData.id,
type: postData.type,
postTitle: postData.title.rendered,
slug: postData.slug,
content: postData.content.rendered,
publishDate: postData.date_gmt + '+00:00',
featuredImage: postData.featured_media,
tags: getPostLabels(postData.tags, 'tags'),
categories: getPostLabels(postData.categories, 'categories'),
contentImages: getPostBodyImages(postData)
}
wpData.posts.push(fieldData)
}
console.log(`...Done!`)
console.log(logSeparator)
writeDataToFile(wpData, 'wpPosts');
createForContentful();
}
function getPostBodyImages(postData) {
// console.log(`- Getting content images`)
let imageRegex = /<img\s[^>]*?src\s*=\s*['\"]([^'\"]*?)['\"][^>]*?>/g
let bodyImages = []
if (postData.featured_media > 0) {
let mediaData = getApiDataType(`media`)[0];
let mediaObj = mediaData.data.filter(obj => {
if (obj.id === postData.featured_media) {
return obj
}
})[0];
bodyImages.push({
link: mediaObj.source_url,
description: mediaObj.alt_text,
title: mediaObj.alt_text,
mediaId: mediaObj.id,
postId: mediaObj.post,
featured: true
})
}
while (foundImage = imageRegex.exec(postData.content.rendered)) {
let alt = postData.id
if (foundImage[0].includes('alt="')) {
alt = foundImage[0].split('alt="')[1].split('"')[0] || ''
}
bodyImages.push({
link: foundImage[1],
description: alt,
title: alt,
postId: postData.id,
featured: false
})
}
return bodyImages
}
function getPostLabels(postItems, labelType) {
let labels = []
let apiTag = getApiDataType(labelType)[0];
for (const labelId of postItems) {
let labelName = apiTag.data.filter(obj => {
if (obj.id === labelId) {
return obj.name
}
});
labels.push(labelName[0].name)
}
return labels
}
/**
* Helper function to get a specific data tree for a type of resource.
* @param {String} resourceName - specific type of WP endpoint (e.g. posts, media)
*/
function getApiDataType(resourceName) {
let apiType = apiData.filter(obj => {
if (obj.endpoint === resourceName) {
return obj
}
});
return apiType
}
/**
* Write all exported WP data to its own JSON file.
* @param {Object} dataTree - JSON body of WordPress data
* @param {*} dataType - type of WordPress API endpoint.
*/
function writeDataToFile(dataTree, dataType) {
console.log(`Writing data to a file`)
fs.writeFile(`./${dataType}.json`, JSON.stringify(dataTree, null, 2), (err) => {
if (err) {
console.error(err);
return;
};
console.log(`...Done!`)
console.log(logSeparator)
});
}
/**
* Create Contentful Client.
*/
function createForContentful() {
ctfClient.getSpace(ctfData.spaceId)
.then((space) => space.getEnvironment(ctfData.environment))
.then((environment) => {
buildContentfulAssets(environment);
})
.catch((error) => {
console.log(error)
return error
})
}
/**
* Build data trees for Contentful assets.
* @param {String} environment - name of Contentful environment.
*/
function buildContentfulAssets(environment) {
let assetPromises = []
console.log('Building Contentful Asset Objects')
// For every image in every post, create a new asset.
for (let [index, wpPost] of wpData.posts.entries()) {
for (const [imgIndex, contentImage] of wpPost.contentImages.entries()) {
let assetObj = {
title: {
'en-GB': contentImage.title
},
description: {
'en-GB': contentImage.description
},
file: {
'en-GB': {
contentType: 'image/jpeg',
fileName: contentImage.link.split('/').pop(),
upload: encodeURI(contentImage.link)
}
}
}
assetPromises.push(assetObj);
}
}
let assets = []
console.log(`Creating Contentful Assets...`)
console.log(logSeparator)
// getAndStoreAssets()
createContentfulAssets(environment, assetPromises, assets)
.then((result) => {
console.log(`...Done!`)
console.log(logSeparator)
getAndStoreAssets(environment, assets)
})
}
/**
* Fetch all published assets from Contentful and store in a variable.
* @param {String} environment - name of Contentful Environment.
* @param {Array} assets - Array to store assets in.
*/
function getAndStoreAssets(environment, assets) {
console.log(`Storing asset URLs in a global array to use later`)
// Not supported with JS? Easier to get all assets and support
axios.get(`https://api.contentful.com/spaces/${ctfData.spaceId}/environments/${ctfData.environment}/public/assets`,
{
headers: {
'Authorization':`Bearer ${ctfData.accessToken}`
}
})
.then((result) => {
// console.log(result)
contentfulData.assets = []
for (const item of result.data.items) {
contentfulData.assets.push(item.fields.file['en-GB'].url)
}
createContentfulPosts(environment, assets)
}).catch((err) => {
console.log(err)
return error
});
console.log(`...Done!`)
console.log(logSeparator)
}
/**
* Create a Promise to publish all assets.
* Note that, Timeout might not be needed here, but Contentful
* rate limits were being hit.
* @param {String} environment - Contentful Environment
* @param {Array} promises - Contentful Asset data trees
* @param {Array} assets - array to store Assets in
*/
function createContentfulAssets(environment, promises, assets) {
return Promise.all(
promises.map((asset, index) => new Promise(async resolve => {
let newAsset
// console.log(`Creating: ${post.slug['en-GB']}`)
setTimeout(() => {
try {
newAsset = environment.createAsset({
fields: asset
})
.then((asset) => asset.processForAllLocales())
.then((asset) => asset.publish())
.then((asset) => {
console.log(`Published Asset: ${asset.fields.file['en-GB'].fileName}`);
assets.push({
assetId: asset.sys.id,
fileName: asset.fields.file['en-GB'].fileName
})
})
} catch (error) {
throw(Error(error))
}
resolve(newAsset)
}, 1000 + (5000 * index));
}))
);
}
/**
* For each WordPress post, build the data for a Contentful counterpart.
* @param {String} environment - Name of Contentful Environment.
* @param {Array} assets - array to store Assets in
*/
function createContentfulPosts(environment, assets) {
console.log(`Creating Contentful Posts...`)
console.log(logSeparator)
// let postFields = {}
/**
* Dynamically build our Contentful data object
* using the keys we built whilst reducing the WP Post data.alias
*
* Results:
* postTitle: {
* 'en-GB': wpPost.postTitle
* },
* slug: {
* 'en-GB': wpPost.slug
* },
*/
let promises = []
for (const [index, post] of wpData.posts.entries()) {
let postFields = {}
for (let [postKey, postValue] of Object.entries(post)) {
// console.log(`postKey: ${postValue}`)
if (postKey === 'content') {
postValue = turndownService.turndown(postValue)
}
/**
* Remove values/flags/checks used for this script that
* Contentful doesn't need.
*/
let keysToSkip = [
'id',
'type',
'contentImages'
]
if (!keysToSkip.includes(postKey)) {
postFields[postKey] = {
'en-GB': postValue
}
}
if (postKey === 'featuredImage' && postValue > 0) {
let assetObj = assets.filter(asset => {
if (asset.fileName === post.contentImages[0].link.split('/').pop()) {
return asset
}
})[0];
postFields.featuredImage = {
'en-GB': {
sys: {
type: 'Link',
linkType: 'Asset',
id: assetObj.assetId
}
}
}
}
// No image and Contentful will fail if value is '0', so remove.
if (postKey === 'featuredImage' && postValue === 0) {
delete postFields.featuredImage
}
}
promises.push(postFields)
}
console.log(`Post objects created, attempting to create entries...`)
createContentfulEntries(environment, promises)
.then((result) => {
console.log(logSeparator);
console.log(`Done!`);
console.log(logSeparator);
console.log(`The migration has completed.`)
console.log(logSeparator);
});
}
/**
* For each post data tree, publish a Contentful entry.
* @param {String} environment - Name of Contentful Environment.
* @param {Array} promises - data trees for Contentful posts.
*/
function createContentfulEntries(environment, promises) {
return Promise.all(promises.map((post, index) => new Promise(async resolve => {
let newPost
console.log(`Attempting: ${post.slug['en-GB']}`)
setTimeout(() => {
try {
newPost = environment.createEntry('blogPost', {
fields: post
})
.then((entry) => entry.publish())
.then((entry) => {
console.log(`Success: ${entry.fields.slug['en-GB']}`)
})
} catch (error) {
throw(Error(error))
}
resolve(newPost)
}, 1000 + (5000 * index));
})));
}
/**
* Convert WordPress content to Contentful Rich Text
* Ideally we'd be using Markdown here, but I like the RichText editor 🤡
*
* Note: Abandoned because it did not seem worth the effort.
* Leaving this here in case anybody does decide to venture this way.
*
* @param {String} content - WordPress post content.
*/
function formatRichTextPost(content) {
// TODO: split at paragraphs, create a node for each.
console.log(logSeparator)
// turndownService.remove('code')
let markdown = turndownService.turndown(content)
// console.log(logSeparator)
// console.log(markdown)
// let imageLinks = /!\[[^\]]*\]\((.*?)\s*("(?:.*[^"])")?\s*\)/g
// let imageRegex = /<img\s[^>]*?src\s*=\s*['\"]([^'\"]*?)['\"][^>]*?>/g
// while (foundImage = imageLinks.exec(markdown)) {
// console.log(foundImage[0])
// let alt = foundImage[0].split('alt="')[1].split('"')[0]
// }
/**
* https://www.contentful.com/developers/docs/concepts/rich-text/
*/
/**
* "expected": [
"blockquote",
"embedded-asset-block",
"embedded-entry-block",
"heading-1",
"heading-2",
"heading-3",
"heading-4",
"heading-5",
"heading-6",
"hr",
"ordered-list",
"paragraph",
"unordered-list"
]
*/
// let contentor = {
// content: [
// {
// nodeType:"paragraph",
// data: {},
// content: [
// {
// value: content,
// nodeType:"text",
// marks: [],
// data: {}
// }
// ]
// },
// // {
// // nodeType:"paragraph",
// // data: {},
// // content: [
// // {
// // value: "lorem hello world two",
// // nodeType:"text",
// // marks: [],
// // data: {}
// // }
// // ]
// // },
// ],
// data: {},
// nodeType: 'document'
// };
return markdown
}
migrateContent();