forked from mdreizin/gatsby-plugin-robots-txt
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgatsby-node.js
More file actions
85 lines (69 loc) · 1.86 KB
/
gatsby-node.js
File metadata and controls
85 lines (69 loc) · 1.86 KB
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
import fs from 'fs';
import robotsTxt from 'generate-robotstxt';
import path from 'path';
import url from 'url';
const publicPath = './public';
const defaultEnv = 'development';
const defaultOptions = {
output: '/robots.txt',
query: `{
site {
siteMetadata {
siteUrl
}
}
}`
};
function writeFile(file, data) {
return new Promise((resolve, reject) => {
fs.writeFile(file, data, err => {
if (err) {
reject(err);
} else {
resolve();
}
});
});
}
function runQuery(handler, query) {
return handler(query).then(res => {
if (res.errors) {
throw new Error(res.errors.join(', '));
}
return res.data;
});
}
const getOptions = pluginOptions => {
const options = { ...pluginOptions };
delete options.plugins;
const { env = {}, resolveEnv = () => process.env.GATSBY_ACTIVE_ENV || process.env.NODE_ENV } = options;
const envOptions = env[resolveEnv()] || env[defaultEnv] || {};
delete options.env;
delete options.resolveEnv;
return { ...options, ...envOptions };
};
export async function onPostBuild({ graphql }, pluginOptions) {
const userOptions = getOptions(pluginOptions);
const mergedOptions = { ...defaultOptions, ...userOptions };
if (
!Object.prototype.hasOwnProperty.call(mergedOptions, 'host') ||
!Object.prototype.hasOwnProperty.call(mergedOptions,'sitemap')
) {
const {
site: {
siteMetadata: { siteUrl }
}
} = await runQuery(graphql, mergedOptions.query);
mergedOptions.host = siteUrl;
mergedOptions.sitemap = url.resolve(siteUrl, 'sitemap.xml');
}
const { policy, sitemap, host, output, configFile } = mergedOptions;
const content = await robotsTxt({
policy,
sitemap,
host,
configFile
});
const filename = path.join(publicPath, output);
return await writeFile(path.resolve(filename), content);
}