Skip to content

Restfit 1.0.11

Latest

Choose a tag to compare

@kyree-henry kyree-henry released this 17 Jan 18:11
· 3 commits to main since this release

Release Notes - Version 1.0.11

New Features

@OnRetrying Decorator

Added a new decorator to handle retry events during resilience operations:

  • @OnRetrying(handler) - Custom retry handler that is called when a request is being retried
    • Handler receives retryCount (number) and error (AxiosError)
    • Method-specific retry handlers override default logging behavior
    • Works in conjunction with the resilience retry policy
    • If retries are disabled, the handler will not be called

Example:

class UserService {
  @Get('/users/{id}')
  @OnRetrying((retryCount, error) => {
    console.log(`🔄 Retry attempt ${retryCount} for user ${error.config?.url}`);
    // Custom retry logic: update metrics, send notifications, etc.
  })
  async getUser(@Path('id') id: number): Promise<User> {
    return {} as User;
  }
}

Automatic Response Wrapping (wrapResponses)

Added a powerful new feature to automatically wrap all responses in a consistent format, similar to Microsoft's API client pattern:

  • wrapResponses: true - Config option to enable automatic response wrapping
  • Eliminates the need for try-catch blocks
  • Provides consistent response structure across all methods
  • Only wraps responses for methods with @OnError handlers (methods without handlers still throw errors)

Response Format:

Success (object):

// Original: { users: [...] }
// Wrapped: { users: [...], success: true }
const { users, success } = await service.getUsers();

Success (array/primitive):

// Original: User[]
// Wrapped: { data: User[], success: true }
const { data, success } = await service.getUsers();

Error:

// { success: false, error: <@OnError handler return value> }
const { success, error } = await service.getUser(999);

Key Benefits:

  • ✅ No try-catch blocks needed for methods with @OnError handlers
  • ✅ Consistent response structure across all methods
  • ✅ Type-safe error handling
  • ✅ Works seamlessly with existing code (method signatures remain unchanged)
  • ✅ Object responses are spread with success added (preserves original property names)
  • ✅ Array/primitive responses are wrapped in { data, success }

Important Notes:

  • Wrapping only occurs for methods that have @OnError handlers
  • Methods without error handlers will still throw errors even when wrapResponses: true
  • The error field contains whatever the @OnError handler returns
  • Object responses preserve their original structure (spread with success added)
  • Array and primitive responses are wrapped in { data, success }

Improvements

Property Naming

  • Renamed isSucceeded to success for better consistency and readability
  • All wrapped responses now use success: boolean instead of isSucceeded: boolean

Usage Example

import { Get, OnError, createApiService } from 'restfit';
import { AxiosError } from 'axios';

class UserService {
  @Get('/users')
  @OnError((error: AxiosError) => {
    return {
      message: error.message || 'Request failed',
      statusCode: error.response?.status
    };
  })
  async getUsers(): Promise<User[]> {
    return [];
  }
}

// Enable automatic response wrapping
const userService = createApiService(UserService, {
  baseUrl: 'https://api.example.com',
  wrapResponses: true,
});

// Usage - no try-catch needed!
const { data: users, success, error } = await userService.getUsers();

if (success) {
  console.log('Users:', users);
} else {
  console.error('Error:', error);
}

Breaking Changes

None - All changes are backward compatible. Existing code continues to work without modification.

Technical Details

@OnRetrying Implementation

  • Retry handlers are stored as metadata on methods
  • Handlers are attached to request config and accessed by the resilience module
  • Method-specific handlers override default retry logging
  • Supports both synchronous and asynchronous handlers

wrapResponses Implementation

  • Wrapping logic is applied in the factory method handler
  • Object responses are spread to preserve original property names
  • Array/primitive responses are wrapped in { data, success }
  • Error responses only wrap when @OnError handlers are present
  • Works seamlessly with @OnSuccess handlers and response interceptors

Migration Guide

If you were using a custom wrapper pattern, you can now use the built-in wrapResponses option:

Before:

try {
  const users = await service.getUsers();
  // handle success
} catch (error) {
  // handle error
}

After:

const { data: users, success, error } = await service.getUsers();
if (success) {
  // handle success
} else {
  // handle error
}