2017-02-26 19:45:16 +00:00
|
|
|
/* global location */
|
|
|
|
|
|
|
|
import Router from '../lib/router'
|
|
|
|
import fetch from 'unfetch'
|
|
|
|
|
2017-04-18 04:18:43 +00:00
|
|
|
export default () => {
|
|
|
|
Router.ready(() => {
|
|
|
|
Router.router.events.on('routeChangeComplete', ping)
|
|
|
|
})
|
2017-03-12 03:51:49 +00:00
|
|
|
|
2017-04-18 04:18:43 +00:00
|
|
|
async function ping () {
|
|
|
|
try {
|
|
|
|
const url = `/_next/on-demand-entries-ping?page=${Router.pathname}`
|
2017-07-08 19:45:34 +00:00
|
|
|
const res = await fetch(url, {
|
|
|
|
credentials: 'same-origin'
|
|
|
|
})
|
2017-04-18 04:18:43 +00:00
|
|
|
const payload = await res.json()
|
|
|
|
if (payload.invalid) {
|
2017-07-02 07:29:08 +00:00
|
|
|
// Payload can be invalid even if the page is not exists.
|
|
|
|
// So, we need to make sure it's exists before reloading.
|
2017-07-08 19:45:34 +00:00
|
|
|
const pageRes = await fetch(location.href, {
|
|
|
|
credentials: 'same-origin'
|
|
|
|
})
|
2017-07-02 07:29:08 +00:00
|
|
|
if (pageRes.status === 200) {
|
|
|
|
location.reload()
|
|
|
|
}
|
2017-04-18 04:18:43 +00:00
|
|
|
}
|
|
|
|
} catch (err) {
|
|
|
|
console.error(`Error with on-demand-entries-ping: ${err.message}`)
|
2017-02-26 19:45:16 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-09-08 21:26:13 +00:00
|
|
|
let pingerTimeout
|
2017-04-18 04:18:43 +00:00
|
|
|
async function runPinger () {
|
2017-09-08 21:26:13 +00:00
|
|
|
// Will restart on the visibilitychange API below. For older browsers, this
|
|
|
|
// will always be true and will always run, but support is fairly prevalent
|
|
|
|
// at this point.
|
|
|
|
while (!document.hidden) {
|
2017-04-18 04:18:43 +00:00
|
|
|
await ping()
|
2017-09-08 21:26:13 +00:00
|
|
|
await new Promise((resolve) => {
|
|
|
|
pingerTimeout = setTimeout(resolve, 5000)
|
|
|
|
})
|
2017-04-18 04:18:43 +00:00
|
|
|
}
|
2017-02-26 19:45:16 +00:00
|
|
|
}
|
|
|
|
|
2017-09-08 21:26:13 +00:00
|
|
|
document.addEventListener('visibilitychange', () => {
|
|
|
|
if (!document.hidden) {
|
|
|
|
runPinger()
|
|
|
|
} else {
|
|
|
|
clearTimeout(pingerTimeout)
|
|
|
|
}
|
|
|
|
}, false)
|
|
|
|
|
|
|
|
setTimeout(() => {
|
|
|
|
runPinger()
|
|
|
|
.catch((err) => {
|
|
|
|
console.error(err)
|
|
|
|
})
|
|
|
|
}, 10000)
|
2017-04-18 04:18:43 +00:00
|
|
|
}
|