UNPKG

@adonisjs/inertia

Version:

Official Inertia.js adapter for AdonisJS

99 lines (98 loc) 3.06 kB
import type { HttpContext } from '@adonisjs/core/http'; import { type Inertia } from './inertia.js'; import type { InertiaPages, PageProps } from './types.js'; declare module '@adonisjs/core/http' { interface HttpContext { inertia: Inertia<InertiaPages>; } } /** * Base middleware class for handling Inertia.js requests * * This middleware handles the initialization of the Inertia instance, * manages request headers, handles redirects for mutation methods, * and implements asset versioning. * * @example * ```ts * export default class InertiaMiddleware extends BaseInertiaMiddleware { * async share() { * return { * user: ctx.auth?.user * } * } * } * ``` */ export default abstract class BaseInertiaMiddleware { /** * Extract validation errors from the session and format them for Inertia * * Retrieves validation errors from the session flash messages and formats * them according to Inertia's error bag conventions. Supports both simple * error objects and error bags for multi-form scenarios. * * @param ctx - The HTTP context containing session data * @returns Formatted validation errors, either as a simple object or error bags * * @example * ```js * const errors = middleware.getValidationErrors(ctx) * // Returns: { email: 'Email is required', password: 'Password too short' } * // Or with error bags: { login: { email: 'Email is required' } } * ``` */ getValidationErrors(ctx: HttpContext): Record<string, string> | { [errorBag: string]: Record<string, string>; }; /** * Share data with all Inertia pages * * This method should return an object containing data that will be * available to all Inertia pages as props. * * @param ctx - The HTTP context object * @returns Props to share across all pages * * @example * ```js * async share() { * return { * user: ctx.auth?.user, * flash: ctx.session?.flashMessages.all() * } * } * ``` */ abstract share?(ctx: HttpContext): PageProps | Promise<PageProps>; /** * Initialize the Inertia instance for the current request * * This method creates an Inertia instance and attaches it to the * HTTP context, making it available throughout the request lifecycle. * * @param ctx - The HTTP context object * * @example * ```ts * await middleware.init(ctx) * ``` */ init(ctx: HttpContext): Promise<void>; /** * Clean up and finalize the Inertia response * * This method handles the final processing of Inertia requests including: * - Setting appropriate response headers * - Handling redirects for mutation methods (PUT/PATCH/DELETE) * - Managing asset versioning conflicts * * @param ctx - The HTTP context object * * @example * ```ts * await middleware.dispose(ctx) * ``` */ dispose(ctx: HttpContext): void; }