Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(gatsby-source-drupal): Use the collection count from JSON:API extras to enable parallel API requests for cold builds #32883

Merged
merged 8 commits into from
Aug 26, 2021
42 changes: 41 additions & 1 deletion packages/gatsby-source-drupal/src/gatsby-node.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ const _ = require(`lodash`)
const urlJoin = require(`url-join`)
import HttpAgent from "agentkeepalive"
// const http2wrapper = require(`http2-wrapper`)
const url = require(`url`)
const querystring = require(`querystring`)
KyleAMathews marked this conversation as resolved.
Show resolved Hide resolved

const { HttpsAgent } = HttpAgent

Expand Down Expand Up @@ -293,6 +295,7 @@ exports.sourceNodes = async (
drupalFetchActivity.start()

let allData
const typeRequestsQueued = new Set()
try {
const res = await requestQueue.push([
urlJoin(baseUrl, apiBase),
Expand Down Expand Up @@ -370,7 +373,44 @@ exports.sourceNodes = async (
if (d.body.included) {
dataArray.push(...d.body.included)
}
if (d.body.links && d.body.links.next) {

// If JSON:API extras is configured to add the resource count, we can queue
// all API requests immediately.
if (d.body.meta?.count) {
// If we hadn't added urls yet
if (
d.body.meta.count > 50 &&
!typeRequestsQueued.has(d.body.data[0]?.type)
) {
KyleAMathews marked this conversation as resolved.
Show resolved Hide resolved
typeRequestsQueued.add(d.body.data[0]?.type)

// Get count of API requests
// We round down as we've already gotten the first page.
const requestsCount = Math.floor(d.body.meta.count / 50)
reporter.verbose(
`queueing ${requestsCount} API requests for type ${d.body.data[0].type} which has ${d.body.meta.count} entities.`
)
if (d.body.links.next?.href) {
const parsedUrl = url.parse(d.body.links.next?.href)
const parsedQueryString = querystring.parse(parsedUrl.query)
await Promise.all(
_.range(requestsCount).map(pageOffset => {
pageOffset += 1
// Construct query string.
const newQuerystring = {
...parsedQueryString,
"page[offset]": pageOffset * 50,
}
const newUrl = url.format({
...parsedUrl,
search: querystring.stringify(newQuerystring),
})
return getNext(newUrl)
})
KyleAMathews marked this conversation as resolved.
Show resolved Hide resolved
)
}
}
} else if (d.body.links?.next) {
await getNext(d.body.links.next)
}
}
Expand Down