Skip to content

Commit

Permalink
Offline flag logic
Browse files Browse the repository at this point in the history
  • Loading branch information
uttrasey committed Feb 11, 2018
1 parent ab1d7f5 commit 13fb510
Showing 1 changed file with 37 additions and 6 deletions.
43 changes: 37 additions & 6 deletions packages/gatsby-source-contentful/src/gatsby-node.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,27 @@ const restrictedNodeFields = [
`parent`,
]

const cmsCacheFilename = `contentful-result.json`

async function writeFetchCache(programDirectory, fetchResult) {
try {
await fs.writeJson(`${programDirectory}/.cache/${cmsCacheFilename}`, fetchResult)
} catch (err) {
console.error(err)
}
}

async function readFetchCache(programDirectory) {
try {
console.time(`Fetch Contentful data`)
console.log(`Using Contentful Offline cache ⚠️`)
return await fs.readJson(`${programDirectory}/.cache/${cmsCacheFilename}`)
} catch (err) {
console.error(err)
}
return null
}

exports.setFieldsOnGraphQLNodeType = require(`./extend-node-type`).extendNodeType

/***
Expand Down Expand Up @@ -53,17 +74,27 @@ exports.sourceNodes = async (
]
}

const programDir = store.getState().program.directory
let fetchResult

if (process.env.GATSBY_CONTENTFUL_OFFLINE === `true`) {
fetchResult = await readFetchCache(programDir)
} else {
fetchResult = await fetchData({
syncToken,
spaceId,
accessToken,
host,
})
writeFetchCache(programDir, fetchResult)
}

const {
currentSyncData,
contentTypeItems,
defaultLocale,
locales,
} = await fetchData({
syncToken,
spaceId,
accessToken,
host,
})
} = fetchResult

const entryList = normalize.buildEntryList({
currentSyncData,
Expand Down

0 comments on commit 13fb510

Please sign in to comment.