Unverified Commit 0957ed6f authored by Joe Haddad's avatar Joe Haddad Committed by GitHub

Use Cached SSG Data on History Navigation (#9887)

* Use Cached SSG Data on History Navigation

* Add data caching test

* Create a static data cache

* Eliminate an if / return

* Do not cache in dev mode

* bump

* bump

* bump

* bump
Co-authored-by: 's avatarJJ Kasper <jj@jjsweb.site>
parent 3ece98b3
...@@ -71,6 +71,8 @@ export default class Router implements BaseRouter { ...@@ -71,6 +71,8 @@ export default class Router implements BaseRouter {
* Map of all components loaded in `Router` * Map of all components loaded in `Router`
*/ */
components: { [pathname: string]: RouteInfo } components: { [pathname: string]: RouteInfo }
// Static Data Cache
sdc: { [asPath: string]: object } = {}
sub: Subscription sub: Subscription
clc: ComponentLoadCancel clc: ComponentLoadCancel
pageLoader: any pageLoader: any
...@@ -656,23 +658,31 @@ export default class Router implements BaseRouter { ...@@ -656,23 +658,31 @@ export default class Router implements BaseRouter {
}) })
} }
_getStaticData = (asPath: string): Promise<any> => { _getStaticData = (asPath: string, _cachedData?: object): Promise<object> => {
let pathname = parse(asPath).pathname let pathname = parse(asPath).pathname
pathname = !pathname || pathname === '/' ? '/index' : pathname pathname = !pathname || pathname === '/' ? '/index' : pathname
return fetch(
// @ts-ignore __NEXT_DATA__ return process.env.NODE_ENV === 'production' &&
`/_next/data/${__NEXT_DATA__.buildId}${pathname}.json` (_cachedData = this.sdc[pathname])
) ? Promise.resolve(_cachedData)
.then(res => { : fetch(
if (!res.ok) { // @ts-ignore __NEXT_DATA__
throw new Error(`Failed to load static props`) `/_next/data/${__NEXT_DATA__.buildId}${pathname}.json`
} )
return res.json() .then(res => {
}) if (!res.ok) {
.catch((err: Error) => { throw new Error(`Failed to load static props`)
;(err as any).code = 'PAGE_LOAD_ERROR' }
throw err return res.json()
}) })
.then(data => {
this.sdc[pathname!] = data
return data
})
.catch((err: Error) => {
;(err as any).code = 'PAGE_LOAD_ERROR'
throw err
})
} }
getInitialProps( getInitialProps(
......
...@@ -26,7 +26,7 @@ export async function unstable_getStaticProps() { ...@@ -26,7 +26,7 @@ export async function unstable_getStaticProps() {
export default ({ world, time }) => ( export default ({ world, time }) => (
<> <>
<p>hello {world}</p> <p>hello {world}</p>
<span>time: {time}</span> <span id="anotherTime">time: {time}</span>
<Link href="/"> <Link href="/">
<a id="home">to home</a> <a id="home">to home</a>
</Link> </Link>
......
...@@ -110,7 +110,7 @@ const expectedManifestRoutes = () => ({ ...@@ -110,7 +110,7 @@ const expectedManifestRoutes = () => ({
}, },
}) })
const navigateTest = () => { const navigateTest = (dev = false) => {
it('should navigate between pages successfully', async () => { it('should navigate between pages successfully', async () => {
const toBuild = [ const toBuild = [
'/', '/',
...@@ -133,18 +133,52 @@ const navigateTest = () => { ...@@ -133,18 +133,52 @@ const navigateTest = () => {
await waitFor(2500) await waitFor(2500)
// go to /another // go to /another
await browser.elementByCss('#another').click() async function goFromHomeToAnother() {
await browser.waitForElementByCss('#home') await browser.elementByCss('#another').click()
text = await browser.elementByCss('p').text() await browser.waitForElementByCss('#home')
expect(text).toMatch(/hello.*?world/) text = await browser.elementByCss('p').text()
expect(text).toMatch(/hello.*?world/)
}
await goFromHomeToAnother()
// go to / // go to /
await browser.eval('window.didTransition = 1') async function goFromAnotherToHome() {
await browser.elementByCss('#home').click() await browser.eval('window.didTransition = 1')
await browser.waitForElementByCss('#another') await browser.elementByCss('#home').click()
text = await browser.elementByCss('p').text() await browser.waitForElementByCss('#another')
expect(text).toMatch(/hello.*?world/) text = await browser.elementByCss('p').text()
expect(await browser.eval('window.didTransition')).toBe(1) expect(text).toMatch(/hello.*?world/)
expect(await browser.eval('window.didTransition')).toBe(1)
}
await goFromAnotherToHome()
// Client-side SSG data caching test
// eslint-disable-next-line no-lone-blocks
{
// Let revalidation period lapse
await waitFor(2000)
// Trigger revalidation (visit page)
await goFromHomeToAnother()
const snapTime = await browser.elementByCss('#anotherTime').text()
// Wait for revalidation to finish
await waitFor(2000)
// Re-visit page
await goFromAnotherToHome()
await goFromHomeToAnother()
const nextTime = await browser.elementByCss('#anotherTime').text()
if (dev) {
expect(snapTime).not.toMatch(nextTime)
} else {
expect(snapTime).toMatch(nextTime)
}
// Reset to Home for next test
await goFromAnotherToHome()
}
// go to /something // go to /something
await browser.elementByCss('#something').click() await browser.elementByCss('#something').click()
...@@ -180,7 +214,7 @@ const navigateTest = () => { ...@@ -180,7 +214,7 @@ const navigateTest = () => {
} }
const runTests = (dev = false) => { const runTests = (dev = false) => {
navigateTest() navigateTest(dev)
it('should SSR normal page correctly', async () => { it('should SSR normal page correctly', async () => {
const html = await renderViaHTTP(appPort, '/') const html = await renderViaHTTP(appPort, '/')
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment