1 | const fs = require('fs');
|
2 | const path = require('path');
|
3 | const { promisify } = require('util');
|
4 | const grayMatter = require('gray-matter');
|
5 | const { createPath } = require('gatsby-page-utils');
|
6 |
|
7 | const readFile = promisify(fs.readFile);
|
8 |
|
9 | class 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 |
|
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 |
|
52 | module.exports = PageCreator;
|