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-04-18 04:18:43 +00:00
|
|
|
async function runPinger () {
|
|
|
|
while (true) {
|
|
|
|
await new Promise((resolve) => setTimeout(resolve, 5000))
|
|
|
|
await ping()
|
|
|
|
}
|
2017-02-26 19:45:16 +00:00
|
|
|
}
|
|
|
|
|
2017-04-18 04:18:43 +00:00
|
|
|
runPinger()
|
|
|
|
.catch((err) => {
|
|
|
|
console.error(err)
|
|
|
|
})
|
|
|
|
}
|