UNPKG

1.69 kBJavaScriptView Raw
1const plugins = require(`./api-runner-browser-plugins`)
2const {
3 getResourcesForPathname,
4 getResourcesForPathnameSync,
5 getResourceURLsForPathname,
6 loadPage,
7 loadPageSync,
8} = require(`./loader`).publicLoader
9
10exports.apiRunner = (api, args = {}, defaultReturn, argTransform) => {
11 // Hooks for gatsby-cypress's API handler
12 if (process.env.CYPRESS_SUPPORT) {
13 if (window.___apiHandler) {
14 window.___apiHandler(api)
15 } else if (window.___resolvedAPIs) {
16 window.___resolvedAPIs.push(api)
17 } else {
18 window.___resolvedAPIs = [api]
19 }
20 }
21
22 let results = plugins.map(plugin => {
23 if (!plugin.plugin[api]) {
24 return undefined
25 }
26
27 // Deprecated April 2019. Use `loadPageSync` instead
28 args.getResourcesForPathnameSync = getResourcesForPathnameSync
29 // Deprecated April 2019. Use `loadPage` instead
30 args.getResourcesForPathname = getResourcesForPathname
31 args.getResourceURLsForPathname = getResourceURLsForPathname
32 args.loadPage = loadPage
33 args.loadPageSync = loadPageSync
34
35 const result = plugin.plugin[api](args, plugin.options)
36 if (result && argTransform) {
37 args = argTransform({ args, result, plugin })
38 }
39 return result
40 })
41
42 // Filter out undefined results.
43 results = results.filter(result => typeof result !== `undefined`)
44
45 if (results.length > 0) {
46 return results
47 } else if (defaultReturn) {
48 return [defaultReturn]
49 } else {
50 return []
51 }
52}
53
54exports.apiRunnerAsync = (api, args, defaultReturn) =>
55 plugins.reduce(
56 (previous, next) =>
57 next.plugin[api]
58 ? previous.then(() => next.plugin[api](args, next.options))
59 : previous,
60 Promise.resolve()
61 )