2017-02-26 19:45:16 +00:00
|
|
|
/* global location */
|
|
|
|
|
2018-11-28 14:03:02 +00:00
|
|
|
import Router from 'next/router'
|
2017-02-26 19:45:16 +00:00
|
|
|
import fetch from 'unfetch'
|
|
|
|
|
2018-07-24 09:24:40 +00:00
|
|
|
export default ({assetPrefix}) => {
|
2017-04-18 04:18:43 +00:00
|
|
|
Router.ready(() => {
|
2018-07-31 19:04:14 +00:00
|
|
|
Router.events.on('routeChangeComplete', ping)
|
2017-04-18 04:18:43 +00:00
|
|
|
})
|
2017-03-12 03:51:49 +00:00
|
|
|
|
2017-04-18 04:18:43 +00:00
|
|
|
async function ping () {
|
|
|
|
try {
|
2018-07-24 09:24:40 +00:00
|
|
|
const url = `${assetPrefix || ''}/_next/on-demand-entries-ping?page=${Router.pathname}`
|
2017-07-08 19:45:34 +00:00
|
|
|
const res = await fetch(url, {
|
2018-08-29 12:52:15 +00:00
|
|
|
credentials: 'same-origin'
|
2017-07-08 19:45:34 +00:00
|
|
|
})
|
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, {
|
2018-08-29 12:52:15 +00:00
|
|
|
credentials: 'same-origin'
|
2017-07-08 19:45:34 +00:00
|
|
|
})
|
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
|
|
|
}
|