UNPKG

1.54 kBJavaScriptView Raw
1const fs = require('fs');
2const path = require('path');
3const { promisify } = require('util');
4const grayMatter = require('gray-matter');
5const { createPath } = require('gatsby-page-utils');
6
7const readFile = promisify(fs.readFile);
8
9class PageCreator {
10 constructor({ store, createPage, deletePage, pagesDirectory }) {
11 this.store = store;
12 this.createPage = createPage;
13 this.deletePage = deletePage;
14 this.pagesDirectory = pagesDirectory;
15 this.pages = {};
16
17 this.create = this.create.bind(this);
18 this.remove = this.remove.bind(this);
19 }
20
21 async create(filePath) {
22 const shouldCreate = !this.pages[filePath];
23 if (shouldCreate) {
24 this.pages[filePath] = true;
25 const componentPath = path.join(this.pagesDirectory, filePath);
26 const content = await readFile(componentPath);
27 const { data: frontmatter } = grayMatter(content);
28
29 this.createPage({
30 path: createPath(filePath),
31 component: componentPath,
32 context: frontmatter,
33 });
34 }
35 }
36
37 remove(filePath) {
38 // Based on - https://github.com/gatsbyjs/gatsby/blob/master/packages/gatsby-plugin-page-creator/src/gatsby-node.js#L69
39 const componentPath = path.join(this.pagesDirectory, filePath);
40 this.store.getState().pages.forEach((page) => {
41 if (page.component === componentPath) {
42 this.deletePage({
43 path: createPath(filePath),
44 component: componentPath,
45 });
46 }
47 });
48 this.pages[filePath] = undefined;
49 }
50}
51
52module.exports = PageCreator;