# 6.3. Validate Return Value Decorates methods and getter properties to validate their return values against a Joi schema. ## Import ```typescript import { ValidateReturnValue, ValidateReturnValueError } from '@triplef/config-factory/validate-return-value'; ``` ## ValidateReturnValue Decorator ### Usage ```typescript import Joi from 'joi'; import { ValidateReturnValue } from '@triplef/config-factory/validate-return-value'; const UserSchema = Joi.object({ id: Joi.number().required(), name: Joi.string().required(), }); class UserService { @ValidateReturnValue(UserSchema) getUser(id: number) { return { id, name: 'John' }; } @ValidateReturnValue(UserSchema) get user() { return { id: 1, name: 'Jane' }; } } const service = new UserService(); service.getUser(1); // Validates return value service.user; // Validates getter return value ``` ### On Getters ```typescript const ConfigSchema = Joi.object({ port: Joi.number().port().required(), env: Joi.string().valid('development', 'production').required(), }); class AppConfig { @ValidateReturnValue(ConfigSchema) get config() { return { port: 3000, env: 'development' }; } } ``` ### On Methods ```typescript const ApiResponseSchema = Joi.object({ data: Joi.any().required(), timestamp: Joi.date().iso().required(), }); class ApiService { @ValidateReturnValue(ApiResponseSchema) fetchData(endpoint: string) { return { data: { endpoint }, timestamp: new Date(), }; } } ``` ## ValidateReturnValueError Thrown when a return value fails Joi validation. ### Class Definition ```typescript class ValidateReturnValueError extends Error { constructor(message?: string, cause?: unknown) { super(message, { cause }); this.name = 'ValidateReturnValueError'; } } ``` ### Properties | Property | Type | Description | |----------|------|-------------| | `name` | `string` | Always `"ValidateReturnValueError"` | | `message` | `string` | Error message (e.g., `"Schema violation"`) | | `cause` | `unknown` | Joi validation details array | ### Usage ```typescript import { ValidateReturnValueError } from '@triplef/config-factory/validate-return-value'; try { const result = service.getUser(1); } catch (error) { if (error instanceof ValidateReturnValueError) { console.log(error.cause); // Joi validation details } } ``` ## Note This decorator is used internally by `@CacheReturnValue` when a Joi schema is provided. You can use it standalone for validation without caching. ## See Also - [6.2. Cache Return Value](6.2-cache-return-value.md) - Decorator that combines caching with validation