Skip to content

6.3 validate return value

wiki[bot] edited this page Aug 23, 2026 · 1 revision

6.3. Validate Return Value

Decorates methods and getter properties to validate their return values against a Joi schema.

Import

import { ValidateReturnValue, ValidateReturnValueError } from '@triplef/config-factory/validate-return-value';

ValidateReturnValue Decorator

Usage

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

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

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

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

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

Clone this wiki locally