import app from '@adonisjs/core/services/app' import { errors } from '@vinejs/vine' /** * The ValidationService handles manual construction of validation errors * that are compatible with the VanillaErrorReporter and AdonisJS Session. */ export class ValidationService { /** * Builds a validation error in the array-of-objects format without throwing it. * Use this when you need the error object itself, e.g. multipart.abort(error). */ make(field: string, message: string, rule: string = 'manual') { return new errors.E_VALIDATION_ERROR([ { field, message, rule, }, ]) } /** * Throws a manual validation error in the array-of-objects format * which prevents the ".reduce is not a function" error in the session. */ throw(field: string, message: string, rule: string = 'manual') { throw this.make(field, message, rule) } /** * Throws multiple manual validation errors at once. */ throwMany(errorObjects: Array<{ field: string; message: string; rule?: string }>) { throw new errors.E_VALIDATION_ERROR( errorObjects.map((err) => ({ field: err.field, message: err.message, rule: err.rule || 'manual', })) ) } } /** * Initialize and export the singleton instance */ let validation: ValidationService await app.booted(async () => { validation = await app.container.make(ValidationService) }) export { validation as default }