Skip to content

Commit

Permalink
Websocket manager use page data (gatsbyjs#13389)
Browse files Browse the repository at this point in the history
* add utils/page-data.read

* read websocket page data from utils/page-data
  • Loading branch information
Moocar committed Jun 2, 2019
1 parent b7745b9 commit 1eeb520
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 15 deletions.
7 changes: 7 additions & 0 deletions packages/gatsby/src/utils/page-data.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,12 @@ const getFilePath = ({ publicDir }, pagePath) => {
return path.join(publicDir, `page-data`, fixedPagePath, `page-data.json`)
}

const read = async ({ publicDir }, pagePath) => {
const filePath = getFilePath({ publicDir }, pagePath)
const rawPageData = await fs.readFile(filePath, `utf-8`)
return JSON.parse(rawPageData)
}

const write = async ({ publicDir }, page, result) => {
const filePath = getFilePath({ publicDir }, page.path)
const body = {
Expand All @@ -17,5 +23,6 @@ const write = async ({ publicDir }, page, result) => {
}

module.exports = {
read,
write,
}
28 changes: 13 additions & 15 deletions packages/gatsby/src/utils/websocket-manager.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
const path = require(`path`)
const { store } = require(`../redux`)
const fs = require(`fs`)
const pageDataUtil = require(`../utils/page-data`)

type QueryResult = {
id: string,
Expand Down Expand Up @@ -32,27 +33,24 @@ const readCachedResults = (dataFileName: string, directory: string): object => {
* @param {string} pagePath Path to a page.
* @param {string} directory Root directory of current project.
*/
const getCachedPageData = (
const getCachedPageData = async (
pagePath: string,
directory: string
): QueryResult => {
const { jsonDataPaths, pages } = store.getState()
const page = pages.get(pagePath)
if (!page) {
return null
}
const dataPath = jsonDataPaths[page.jsonName]
if (typeof dataPath === `undefined`) {
const { program } = store.getState()
const publicDir = path.join(program.directory, `public`)
try {
const pageData = await pageDataUtil.read({ publicDir }, pagePath)
return {
result: pageData.result,
id: pagePath,
}
} catch (err) {
console.log(
`Error loading a result for the page query in "${pagePath}". Query was not run and no cached result was found.`
)
return undefined
}

return {
result: readCachedResults(dataPath, directory),
id: pagePath,
}
}

/**
Expand Down Expand Up @@ -156,9 +154,9 @@ class WebsocketManager {
}
}

const getDataForPath = path => {
const getDataForPath = async path => {
if (!this.pageResults.has(path)) {
const result = getCachedPageData(path, this.programDir)
const result = await getCachedPageData(path, this.programDir)
if (result) {
this.pageResults.set(path, result)
} else {
Expand Down

0 comments on commit 1eeb520

Please sign in to comment.