1 | "use strict";
|
2 |
|
3 | const fs = require(`fs-extra`);
|
4 |
|
5 | const path = require(`path`);
|
6 |
|
7 | const {
|
8 | store
|
9 | } = require(`../redux`);
|
10 |
|
11 | const getFilePath = ({
|
12 | publicDir
|
13 | }, pagePath) => {
|
14 | const fixedPagePath = pagePath === `/` ? `index` : pagePath;
|
15 | return path.join(publicDir, `page-data`, fixedPagePath, `page-data.json`);
|
16 | };
|
17 |
|
18 | const read = async ({
|
19 | publicDir
|
20 | }, pagePath) => {
|
21 | const filePath = getFilePath({
|
22 | publicDir
|
23 | }, pagePath);
|
24 | const rawPageData = await fs.readFile(filePath, `utf-8`);
|
25 | return JSON.parse(rawPageData);
|
26 | };
|
27 |
|
28 | const write = async ({
|
29 | publicDir
|
30 | }, page, result) => {
|
31 | const filePath = getFilePath({
|
32 | publicDir
|
33 | }, page.path);
|
34 | const body = {
|
35 | componentChunkName: page.componentChunkName,
|
36 | path: page.path,
|
37 | matchPath: page.matchPath,
|
38 | result
|
39 | };
|
40 | const bodyStr = JSON.stringify(body);
|
41 |
|
42 | const pageDataSize = Buffer.byteLength(bodyStr) / 1000;
|
43 | store.dispatch({
|
44 | type: `ADD_PAGE_DATA_STATS`,
|
45 | payload: {
|
46 | filePath,
|
47 | size: pageDataSize
|
48 | }
|
49 | });
|
50 | await fs.outputFile(filePath, bodyStr);
|
51 | };
|
52 |
|
53 | module.exports = {
|
54 | read,
|
55 | write
|
56 | };
|
57 |
|
\ | No newline at end of file |