-
Notifications
You must be signed in to change notification settings - Fork 10.3k
/
fetch.js
620 lines (555 loc) · 14.7 KB
/
fetch.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
const querystring = require(`querystring`)
const axios = require(`axios`)
const _ = require(`lodash`)
const minimatch = require(`minimatch`)
const colorized = require(`./output-color`)
const httpExceptionHandler = require(`./http-exception-handler`)
const requestInQueue = require(`./request-in-queue`)
/**
* Check auth object to see if we should fetch JWT access token
*/
const shouldUseJwt = auth => auth && (auth.jwt_user || auth.jwt_pass)
/**
* Check auth object to see if we should use HTTP Basic Auth
*/
const shouldUseHtaccess = auth =>
auth && (auth.htaccess_user || auth.htaccess_pass)
/**
* Format Auth settings for verbose output
*/
const formatAuthSettings = auth => {
let authOutputLines = []
if (shouldUseJwt(auth)) {
authOutputLines.push(` JWT Auth: ${auth.jwt_user}:${auth.jwt_pass}`)
}
if (shouldUseHtaccess(auth)) {
authOutputLines.push(
` HTTP Basic Auth: ${auth.htaccess_user}:${auth.htaccess_pass}`
)
}
return authOutputLines.join(`\n`)
}
/**
* High-level function to coordinate fetching data from a WordPress
* site.
*/
async function fetch({
baseUrl,
_verbose,
_siteURL,
_useACF,
_acfOptionPageIds,
_hostingWPCOM,
_auth,
_perPage,
_concurrentRequests,
_includedRoutes,
_excludedRoutes,
typePrefix,
refactoredEntityTypes,
}) {
// If the site is hosted on wordpress.com, the API Route differs.
// Same entity types are exposed (excepted for medias and users which need auth)
// but the data model contain slights variations.
let url
let _accessToken
if (_hostingWPCOM) {
url = `https://public-api.wordpress.com/wp/v2/sites/${baseUrl}`
_accessToken = await getWPCOMAccessToken(_auth)
} else {
url = `${_siteURL}/wp-json`
if (shouldUseJwt(_auth)) {
_accessToken = await getJWToken(_auth, url)
}
}
if (_verbose) {
console.time(`=END PLUGIN=====================================`)
const authOutput = formatAuthSettings(_auth)
console.log(
colorized.out(
`
=START PLUGIN=====================================
Site URL: ${_siteURL}
Site hosted on Wordpress.com: ${_hostingWPCOM}
Using ACF: ${_useACF}
Auth: ${authOutput ? `\n${authOutput}` : `false`}
Verbose output: ${_verbose}
Mama Route URL: ${url}
`,
colorized.color.Font.FgBlue
)
)
}
// Call the main API Route to discover the all the routes exposed on this API.
let allRoutes
try {
let options = {
method: `get`,
url: url,
}
if (shouldUseHtaccess(_auth)) {
options.auth = {
username: _auth.htaccess_user,
password: _auth.htaccess_pass,
}
}
if (_accessToken) {
options.headers = {
Authorization: `Bearer ${_accessToken}`,
}
}
allRoutes = await axios(options)
} catch (e) {
httpExceptionHandler(e)
}
let entities = [
{
__type: `wordpress__site_metadata`,
name: allRoutes.data.name,
description: allRoutes.data.description,
url: allRoutes.data.url,
home: allRoutes.data.home,
},
]
if (allRoutes) {
let validRoutes = getValidRoutes({
allRoutes,
url,
_verbose,
_useACF,
_acfOptionPageIds,
_includedRoutes,
_excludedRoutes,
typePrefix,
refactoredEntityTypes,
})
if (_verbose) {
console.log(
colorized.out(
`
Fetching the JSON data from ${validRoutes.length} valid API Routes...
`,
colorized.color.Font.FgBlue
)
)
}
for (let route of validRoutes) {
entities = entities.concat(
await fetchData({
route,
_verbose,
_perPage,
_auth,
_accessToken,
_concurrentRequests,
})
)
if (_verbose) console.log(``)
}
if (_verbose)
console.timeEnd(`=END PLUGIN=====================================`)
} else {
console.log(
colorized.out(`No routes to fetch. Ending.`, colorized.color.Font.FgRed)
)
}
return entities
}
/**
* Gets wordpress.com access token so it can fetch private data like medias :/
*
* @returns
*/
async function getWPCOMAccessToken(_auth) {
let result
const oauthUrl = `https://public-api.wordpress.com/oauth2/token`
try {
let options = {
url: oauthUrl,
method: `post`,
data: querystring.stringify({
client_secret: _auth.wpcom_app_clientSecret,
client_id: _auth.wpcom_app_clientId,
username: _auth.wpcom_user,
password: _auth.wpcom_pass,
grant_type: `password`,
}),
}
result = await axios(options)
result = result.data.access_token
} catch (e) {
httpExceptionHandler(e)
}
return result
}
/**
* Gets JSON Web Token so it can fetch private data
*
* @returns
*/
async function getJWToken(_auth, url) {
let result
let authUrl = `${url}/jwt-auth/v1/token`
try {
const options = {
url: authUrl,
method: `post`,
data: {
username: _auth.jwt_user,
password: _auth.jwt_pass,
},
}
result = await axios(options)
result = result.data.token
} catch (e) {
httpExceptionHandler(e)
}
return result
}
/**
* Fetch the data from specified route url, using the auth provided.
*
* @param {any} route
* @param {any} createNode
*/
async function fetchData({
route,
_verbose,
_perPage,
_auth,
_accessToken,
_concurrentRequests,
}) {
const { type, url, optionPageId } = route
if (_verbose) {
console.log(
colorized.out(
`=== [ Fetching ${type} ] ===`,
colorized.color.Font.FgBlue
),
url
)
console.time(`Fetching the ${type} took`)
}
let routeResponse = await getPages({
url,
_perPage,
_auth,
_accessToken,
_verbose,
_concurrentRequests,
})
let entities = []
if (routeResponse) {
// Process entities to creating GraphQL Nodes.
if (Array.isArray(routeResponse)) {
routeResponse = routeResponse.map(r => {
return {
...r,
...(optionPageId ? { __acfOptionPageId: optionPageId } : {}),
__type: type,
}
})
entities = entities.concat(routeResponse)
} else {
routeResponse.__type = type
if (optionPageId) {
routeResponse.__acfOptionPageId = optionPageId
}
entities.push(routeResponse)
}
// WordPress exposes the menu items in meta links.
if (type == `wordpress__wp_api_menus_menus`) {
for (let menu of routeResponse) {
if (menu.meta && menu.meta.links && menu.meta.links.self) {
entities = entities.concat(
await fetchData({
route: { url: menu.meta.links.self, type: `${type}_items` },
_verbose,
_perPage,
_auth,
_accessToken,
})
)
}
}
}
// TODO : Get the number of created nodes using the nodes in state.
let length
if (routeResponse && Array.isArray(routeResponse)) {
length = routeResponse.length
} else if (routeResponse && !Array.isArray(routeResponse)) {
length = Object.keys(routeResponse).length
}
console.log(
colorized.out(
` -> ${type} fetched : ${length}`,
colorized.color.Font.FgGreen
)
)
}
if (_verbose) {
console.timeEnd(`Fetching the ${type} took`)
}
return entities
}
/**
* Get the pages of data
*
* @param {any} url
* @param {number} [page=1]
* @returns
*/
async function getPages(
{ url, _perPage, _auth, _accessToken, _concurrentRequests, _verbose },
page = 1
) {
try {
let result = []
const getOptions = page => {
let o = {
method: `get`,
url: `${url}?${querystring.stringify({
per_page: _perPage,
page: page,
})}`,
}
if (_accessToken) {
o.headers = {
Authorization: `Bearer ${_accessToken}`,
}
}
if (shouldUseHtaccess(_auth)) {
o.auth = {
username: _auth.htaccess_user,
password: _auth.htaccess_pass,
}
}
return o
}
// Initial request gets the first page of data
// but also the total count of objects, used for
// multiple concurrent requests (rather than waterfall)
const options = getOptions(page)
const { headers, data } = await axios(options)
result = result.concat(data)
// Some resources have no paging, e.g. `/types`
const wpTotal = headers[`x-wp-total`]
const total = parseInt(wpTotal)
const totalPages = parseInt(headers[`x-wp-totalpages`])
if (!wpTotal || totalPages <= 1) {
return result
}
if (_verbose) {
console.log(`
Total entities : ${total}
Pages to be requested : ${totalPages}`)
}
// We got page 1, now we want pages 2 through totalPages
const pageOptions = _.range(2, totalPages + 1).map(getPage =>
getOptions(getPage)
)
const pages = await requestInQueue(pageOptions, {
concurrent: _concurrentRequests,
})
const pageData = pages.map(page => page.data)
pageData.forEach(list => {
result = result.concat(list)
})
return result
} catch (e) {
return httpExceptionHandler(e)
}
}
/**
* Check a route against the whitelist or blacklist
* to determine validity.
*
* @param {any} routePath
* @param {Array} routeList
* @returns {boolean}
*/
function checkRouteList(routePath, routeList) {
return routeList.some(route => minimatch(routePath, route))
}
/**
* Extract valid routes and format its data.
*
* @param {any} allRoutes
* @param {any} url
* @returns
*/
function getValidRoutes({
allRoutes,
url,
_verbose,
_useACF,
_acfOptionPageIds,
_hostingWPCOM,
_includedRoutes,
_excludedRoutes,
typePrefix,
refactoredEntityTypes,
}) {
let validRoutes = []
if (_useACF) {
let defaultAcfNamespace = `acf/v3`
// Grab ACF Version from namespaces
const acfNamespace = allRoutes.data.namespaces
? allRoutes.data.namespaces.find(namespace => namespace.includes(`acf`))
: null
const acfRestNamespace = acfNamespace ? acfNamespace : defaultAcfNamespace
_includedRoutes.push(`/${acfRestNamespace}/**`)
if (_verbose)
console.log(
colorized.out(
`Detected ACF to REST namespace: ${acfRestNamespace}.`,
colorized.color.Font.FgGreen
)
)
// The OPTIONS ACF API Route is not giving a valid _link so let`s add it manually
// and pass ACF option page ID
// ACF to REST v3 requires options/options
let optionsRoute = acfRestNamespace.includes(`3`)
? `options/options/`
: `options/`
validRoutes.push({
url: `${url}/${acfRestNamespace}/${optionsRoute}`,
type: `${typePrefix}acf_options`,
})
// ACF to REST V2 does not allow ACF Option Page ID specification
if (_acfOptionPageIds.length > 0 && acfRestNamespace.includes(`3`)) {
_acfOptionPageIds.forEach(function(acfOptionPageId) {
validRoutes.push({
url: `${url}/acf/v3/options/${acfOptionPageId}`,
type: `${typePrefix}acf_options`,
optionPageId: acfOptionPageId,
})
})
if (_verbose)
console.log(
colorized.out(
`Added ACF Options route(s).`,
colorized.color.Font.FgGreen
)
)
}
if (_acfOptionPageIds.length > 0 && _hostingWPCOM) {
// TODO : Need to test that out with ACF on Wordpress.com hosted site. Need a premium account on wp.com to install extensions.
if (_verbose)
console.log(
colorized.out(
`The ACF options pages is untested under wordpress.com hosting. Please let me know if it works.`,
colorized.color.Effect.Blink
)
)
}
}
for (let key of Object.keys(allRoutes.data.routes)) {
if (_verbose) console.log(`Route discovered :`, key)
let route = allRoutes.data.routes[key]
// A valid route exposes its _links (for now)
if (route._links) {
const entityType = getRawEntityType(route)
// Excluding the "technical" API Routes
const excludedTypes = [
`/v2/**`,
`/v3/**`,
`**/1.0`,
`**/2.0`,
`**/embed`,
`**/proxy`,
`/`,
`/jwt-auth/**`,
]
const routePath = getRoutePath(url, route._links.self)
const whiteList = _includedRoutes
const blackList = [...excludedTypes, ..._excludedRoutes]
// Check whitelist first
const inWhiteList = checkRouteList(routePath, whiteList)
// Then blacklist
const inBlackList = checkRouteList(routePath, blackList)
const validRoute = inWhiteList && !inBlackList
if (validRoute) {
if (_verbose)
console.log(
colorized.out(
`Valid route found. Will try to fetch.`,
colorized.color.Font.FgGreen
)
)
const manufacturer = getManufacturer(route)
let rawType = ``
if (manufacturer === `wp`) {
rawType = `${typePrefix}${entityType}`
}
let validType
switch (rawType) {
case `${typePrefix}posts`:
validType = refactoredEntityTypes.post
break
case `${typePrefix}pages`:
validType = refactoredEntityTypes.page
break
case `${typePrefix}tags`:
validType = refactoredEntityTypes.tag
break
case `${typePrefix}categories`:
validType = refactoredEntityTypes.category
break
default:
validType = `${typePrefix}${manufacturer.replace(
/-/g,
`_`
)}_${entityType.replace(/-/g, `_`)}`
break
}
validRoutes.push({ url: route._links.self, type: validType })
} else {
if (_verbose) {
const invalidType = inBlackList ? `blacklisted` : `not whitelisted`
console.log(
colorized.out(
`Excluded route: ${invalidType}`,
colorized.color.Font.FgYellow
)
)
}
}
} else {
if (_verbose)
console.log(
colorized.out(
`Invalid route: detail route`,
colorized.color.Font.FgRed
)
)
}
}
return validRoutes
}
/**
* Extract the raw entity type from route
*
* @param {any} route
*/
const getRawEntityType = route =>
route._links.self.substring(
route._links.self.lastIndexOf(`/`) + 1,
route._links.self.length
)
/**
* Extract the route path for an endpoint
*
* @param {any} baseUrl The base site URL that should be removed
* @param {any} fullUrl The full URL to retrieve the route path from
*/
const getRoutePath = (baseUrl, fullUrl) => fullUrl.replace(baseUrl, ``)
/**
* Extract the route manufacturer
*
* @param {any} route
*/
const getManufacturer = route =>
route.namespace.substring(0, route.namespace.lastIndexOf(`/`))
module.exports = fetch