2023-02-16 12:56:14 +00:00
|
|
|
import { createError, showError } from '#app/composables/error'
|
2023-05-03 10:02:07 +00:00
|
|
|
import { useNuxtApp } from '#app/nuxt'
|
2023-02-16 12:56:14 +00:00
|
|
|
import { defineNuxtRouteMiddleware, useRouter } from '#app/composables/router'
|
2022-10-10 10:18:20 +00:00
|
|
|
|
|
|
|
export default defineNuxtRouteMiddleware(async (to) => {
|
|
|
|
if (!to.meta?.validate) { return }
|
|
|
|
|
2023-02-16 12:56:14 +00:00
|
|
|
const nuxtApp = useNuxtApp()
|
|
|
|
const router = useRouter()
|
|
|
|
|
2022-10-10 10:18:20 +00:00
|
|
|
const result = await Promise.resolve(to.meta.validate(to))
|
2023-01-14 00:23:20 +00:00
|
|
|
if (result === true) {
|
|
|
|
return
|
2022-10-10 10:18:20 +00:00
|
|
|
}
|
2023-02-16 12:56:14 +00:00
|
|
|
if (process.server) {
|
|
|
|
return result
|
|
|
|
}
|
|
|
|
const error = createError({
|
|
|
|
statusCode: 404,
|
|
|
|
statusMessage: `Page Not Found: ${to.fullPath}`
|
|
|
|
})
|
|
|
|
const unsub = router.beforeResolve((final) => {
|
|
|
|
unsub()
|
|
|
|
if (final === to) {
|
|
|
|
const unsub = router.afterEach(async () => {
|
|
|
|
unsub()
|
2023-05-03 10:02:07 +00:00
|
|
|
await nuxtApp.runWithContext(() => showError(error))
|
2023-02-16 12:56:14 +00:00
|
|
|
// We pretend to have navigated to the invalid route so
|
|
|
|
// that the user can return to the previous page with
|
|
|
|
// the back button.
|
|
|
|
window.history.pushState({}, '', to.fullPath)
|
|
|
|
})
|
|
|
|
// We stop the navigation immediately before it resolves
|
|
|
|
// if there is no other route matching it.
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
})
|
2022-10-10 10:18:20 +00:00
|
|
|
})
|