未验证 提交 c9041260 编写于 作者: J Joe Haddad 提交者: GitHub

refactor(on-demand-entries): extract method: setupPing (#6483)

* refactor(on-demand-entries): extract method: setupPing

* Missed a call
上级 8ae1cd35
/* global window, location */
/* global window */
import Router from 'next/router'
import fetch from 'unfetch'
let evtSource
let currentPage
let retryTimeout
const retryWait = 5000
import { setupPing, currentPage } from './on-demand-entries-utils'
export default async ({ assetPrefix }) => {
Router.ready(() => {
Router.events.on('routeChangeComplete', setupPing)
Router.events.on(
'routeChangeComplete',
setupPing.bind(this, assetPrefix, () => Router.pathname)
)
})
function setupPing (retry) {
// Make sure to only create new EventSource request if page has changed
if (Router.pathname === currentPage && !retry) return
// close current EventSource connection
if (evtSource) {
evtSource.close()
}
currentPage = Router.pathname
const url = `${assetPrefix}/_next/on-demand-entries-ping?page=${currentPage}`
evtSource = new window.EventSource(url)
evtSource.onerror = () => {
retryTimeout = setTimeout(() => setupPing(true), retryWait)
}
evtSource.onopen = () => {
clearTimeout(retryTimeout)
}
evtSource.onmessage = event => {
try {
const payload = JSON.parse(event.data)
if (payload.invalid) {
// Payload can be invalid even if the page does not exist.
// So, we need to make sure it exists before reloading.
fetch(location.href, {
credentials: 'same-origin'
}).then(pageRes => {
if (pageRes.status === 200) {
location.reload()
}
})
}
} catch (err) {
console.error('on-demand-entries failed to parse response', err)
}
}
}
setupPing(currentPage)
setupPing(assetPrefix, () => Router.pathname, currentPage)
}
/* global window, location */
import fetch from 'unfetch'
let evtSource
export let currentPage
let retryTimeout
const retryWait = 5000
export function setupPing (assetPrefix, pathnameFn, retry) {
const pathname = pathnameFn()
// Make sure to only create new EventSource request if page has changed
if (pathname === currentPage && !retry) return
// close current EventSource connection
if (evtSource) {
evtSource.close()
}
currentPage = pathname
const url = `${assetPrefix}/_next/on-demand-entries-ping?page=${currentPage}`
evtSource = new window.EventSource(url)
evtSource.onerror = () => {
retryTimeout = setTimeout(
() => setupPing(assetPrefix, pathnameFn, true),
retryWait
)
}
evtSource.onopen = () => {
clearTimeout(retryTimeout)
}
evtSource.onmessage = event => {
try {
const payload = JSON.parse(event.data)
if (payload.invalid) {
// Payload can be invalid even if the page does not exist.
// So, we need to make sure it exists before reloading.
fetch(location.href, {
credentials: 'same-origin'
}).then(pageRes => {
if (pageRes.status === 200) {
location.reload()
}
})
}
} catch (err) {
console.error('on-demand-entries failed to parse response', err)
}
}
}
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册