-
-
Notifications
You must be signed in to change notification settings - Fork 0
6.3 validate return value
wiki[bot] edited this page Aug 23, 2026
·
1 revision
Decorates methods and getter properties to validate their return values against a Joi schema.
import { ValidateReturnValue, ValidateReturnValueError } from '@triplef/config-factory/validate-return-value';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 valueconst 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' };
}
}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(),
};
}
}Thrown when a return value fails Joi validation.
class ValidateReturnValueError extends Error {
constructor(message?: string, cause?: unknown) {
super(message, { cause });
this.name = 'ValidateReturnValueError';
}
}| Property | Type | Description |
|---|---|---|
name |
string |
Always "ValidateReturnValueError"
|
message |
string |
Error message (e.g., "Schema violation") |
cause |
unknown |
Joi validation details array |
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
}
}This decorator is used internally by @CacheReturnValue when a Joi schema is provided. You can use it standalone for validation without caching.
- 6.2. Cache Return Value - Decorator that combines caching with validation