|
| 1 | +import path from "path" |
1 | 2 | import { formatLogMessage } from "~/utils/format-log-message"
|
2 | 3 | import isInteger from "lodash/isInteger"
|
3 | 4 | import { IPluginOptions } from "~/models/gatsby-api"
|
4 | 5 | import { GatsbyNodeApiHelpers } from "~/utils/gatsby-types"
|
| 6 | +import { usingGatsbyV4OrGreater } from "~/utils/gatsby-version" |
5 | 7 | interface IProcessorOptions {
|
6 | 8 | userPluginOptions: IPluginOptions
|
7 | 9 | helpers: GatsbyNodeApiHelpers
|
@@ -46,6 +48,60 @@ const optionsProcessors: Array<IOptionsProcessor> = [
|
46 | 48 |
|
47 | 49 | delete userPluginOptions.schema.queryDepth
|
48 | 50 |
|
| 51 | + return userPluginOptions |
| 52 | + }, |
| 53 | + }, |
| 54 | + { |
| 55 | + name: `Require beforeChangeNode type setting functions by absolute or relative path`, |
| 56 | + test: ({ userPluginOptions }: IProcessorOptions): boolean => |
| 57 | + !!userPluginOptions?.type, |
| 58 | + processor: ({ |
| 59 | + helpers, |
| 60 | + userPluginOptions, |
| 61 | + }: IProcessorOptions): IPluginOptions => { |
| 62 | + const gatsbyStore = helpers.store.getState() |
| 63 | + const typeSettings = Object.entries(userPluginOptions.type) |
| 64 | + |
| 65 | + typeSettings.forEach(([typeName, settings]) => { |
| 66 | + const beforeChangeNodePath = settings?.beforeChangeNode |
| 67 | + |
| 68 | + if ( |
| 69 | + usingGatsbyV4OrGreater && |
| 70 | + typeof beforeChangeNodePath === `function` |
| 71 | + ) { |
| 72 | + helpers.reporter.panic( |
| 73 | + `Since Gatsby v4+ you cannot use the ${typeName}.beforeChangeNode option as a function. Please make the option a relative or absolute path to a JS file where the beforeChangeNode fn is the default export.` |
| 74 | + ) |
| 75 | + } |
| 76 | + |
| 77 | + if (!beforeChangeNodePath || typeof beforeChangeNodePath !== `string`) { |
| 78 | + return |
| 79 | + } |
| 80 | + |
| 81 | + try { |
| 82 | + const absoluteRequirePath: string | undefined = path.isAbsolute( |
| 83 | + beforeChangeNodePath |
| 84 | + ) |
| 85 | + ? beforeChangeNodePath |
| 86 | + : require.resolve( |
| 87 | + path.join(gatsbyStore.program.directory, beforeChangeNodePath) |
| 88 | + ) |
| 89 | + |
| 90 | + const beforeChangeNodeFn = require(absoluteRequirePath) |
| 91 | + |
| 92 | + if (beforeChangeNodeFn) { |
| 93 | + userPluginOptions.type[typeName].beforeChangeNode = |
| 94 | + beforeChangeNodeFn |
| 95 | + } |
| 96 | + } catch (e) { |
| 97 | + helpers.reporter.panic( |
| 98 | + formatLogMessage( |
| 99 | + `beforeChangeNode type setting for ${typeName} threw error:\n${e.message}` |
| 100 | + ) |
| 101 | + ) |
| 102 | + } |
| 103 | + }) |
| 104 | + |
49 | 105 | return userPluginOptions
|
50 | 106 | },
|
51 | 107 | },
|
|
0 commit comments