diff --git a/src/inertia-helpers/index.ts b/src/inertia-helpers/index.ts index 043f001..8a0c950 100644 --- a/src/inertia-helpers/index.ts +++ b/src/inertia-helpers/index.ts @@ -1,9 +1,24 @@ -export async function resolvePageComponent(path: string, pages: Record | (() => Promise)>): Promise { - const page = pages[path] +export async function resolvePageComponent(path: string, pages: Record | (() => Promise)>, fallback?: string|((path: string) => Promise)): Promise { + let page = pages[path] - if (typeof page === 'undefined') { - throw new Error(`Page not found: ${path}`) + if (typeof page === 'undefined' && typeof fallback === 'string') { + page = pages[fallback] } - return typeof page === 'function' ? page() : page + if (typeof page !== 'undefined') { + return typeof page === 'function' ? page() : page + } + + if (typeof fallback === 'function') { + return fallback(path) + } + + throw new PageNotFoundError(`Page not found: [${path}].`) +} + +export class PageNotFoundError extends Error { + constructor(message: string) { + super(message) + this.name = 'PageNotFoundError' + } } diff --git a/tests/index.test.ts b/tests/index.test.ts index 66ff7cc..ccba367 100644 --- a/tests/index.test.ts +++ b/tests/index.test.ts @@ -1,6 +1,6 @@ import { afterEach, describe, expect, it, vi } from 'vitest' import laravel from '../src' -import { resolvePageComponent } from '../src/inertia-helpers'; +import { resolvePageComponent, PageNotFoundError } from '../src/inertia-helpers'; describe('laravel-vite-plugin', () => { afterEach(() => { @@ -376,4 +376,25 @@ describe('inertia-helpers', () => { const file = await resolvePageComponent<{ default: string }>(path, import.meta.glob('./__data__/*.ts', { eager: true })) expect(file.default).toBe('Dummy File') }) + + it('accepts path as fallback', async () => { + const file = await resolvePageComponent<{ default: string }>('missing-page', import.meta.glob('./__data__/*.ts', { eager: true }), path) + expect(file.default).toBe('Dummy File') + }) + + it('accepts closure as fallback', async () => { + let capturedPath: string|null = null; + const file = await resolvePageComponent<{ default: string }>('missing-page', import.meta.glob('./__data__/*.ts', { eager: true }), (originalPath) => { + capturedPath = originalPath + + return resolvePageComponent<{ default: string }>(path, import.meta.glob('./__data__/*.ts', { eager: true })) + }) + expect(file.default).toBe('Dummy File') + expect(capturedPath).toBe('missing-page') + }) + + it('throws PageNotFoundError when path is not found', async () => { + const callback = () => resolvePageComponent<{ default: string }>('./__data__/_does_not_exist_.ts', import.meta.glob('./__data__/*.ts')) + await expect(callback).rejects.toThrowError(PageNotFoundError) + }) })