|
| 1 | +const path = require('path'); |
1 | 2 | require('dotenv').config(); |
2 | 3 | const Sourcebit = require('./lib/sourcebit'); |
3 | 4 |
|
4 | 5 | module.exports.fetch = (config, runtimeParameters, transformCallback) => { |
5 | | - if (!config) { |
6 | | - throw new Error('ERROR: Could not find a valid `sourcebit.js` configuration file.'); |
7 | | - } |
8 | | - |
9 | 6 | if (typeof runtimeParameters === 'function') { |
10 | 7 | transformCallback = runtimeParameters; |
11 | 8 | runtimeParameters = {}; |
12 | 9 | } |
13 | 10 |
|
| 11 | + const transformDataPromise = fetch(config, runtimeParameters, transformCallback) |
| 12 | + |
| 13 | + if (typeof transformCallback !== 'function') { |
| 14 | + return transformDataPromise; |
| 15 | + } |
| 16 | +}; |
| 17 | + |
| 18 | +module.exports.sourcebitNext = ({ config, runtimeParameters, transformCallback } = {}) => { |
| 19 | + return function withSourcebit(nextConfig) { |
| 20 | + return { |
| 21 | + ...nextConfig, |
| 22 | + // Since Next.js doesn't provide some kind of real "plugin system" |
| 23 | + // we're (ab)using the `redirects` option here in order to hook into |
| 24 | + // and block the `next build` and initial `next dev` run. |
| 25 | + redirects: async () => { |
| 26 | + await fetch(config, runtimeParameters, transformCallback); |
| 27 | + return nextConfig.redirects ? nextConfig.redirects() : []; |
| 28 | + } |
| 29 | + } |
| 30 | + } |
| 31 | +}; |
| 32 | + |
| 33 | +async function fetch(config, runtimeParameters, transformCallback) { |
| 34 | + if (!config) { |
| 35 | + try { |
| 36 | + const configPath = path.resolve(process.cwd(), 'sourcebit.js'); |
| 37 | + config = require(configPath); |
| 38 | + } catch (error) { |
| 39 | + if (error.code === 'MODULE_NOT_FOUND') { |
| 40 | + throw new Error('Could not find sourcebit.js configuration file'); |
| 41 | + } |
| 42 | + throw error; |
| 43 | + } |
| 44 | + } |
14 | 45 | const instance = new Sourcebit({ runtimeParameters, transformCallback }); |
15 | 46 | const { plugins = [] } = config; |
16 | 47 |
|
17 | 48 | instance.loadPlugins(plugins); |
18 | 49 |
|
19 | | - const transformData = instance.bootstrapAll().then(() => instance.transform()); |
20 | | - |
21 | | - if (typeof transformCallback !== 'function') { |
22 | | - return transformData; |
23 | | - } |
24 | | -}; |
| 50 | + return instance.bootstrapAll().then(() => instance.transform()); |
| 51 | +} |
25 | 52 |
|
26 | 53 | module.exports.Sourcebit = Sourcebit; |
0 commit comments