AbstractCreate a new transformer instance with the provided resource data.
This constructor is typically not called directly. Instead, use the static
transform method to create Item or Collection instances.
The raw resource data to be transformed
class UserTransformer extends BaseTransformer<User> {
constructor(user: User) {
super(user)
}
}
StatictransformTransform data wrapped in Maybe that can be undefined
Maybe-wrapped data that can be undefined
Transform a single data object
Single data object to transform
Transform data wrapped in Maybe that can be undefined or null
Maybe-wrapped data that can be undefined or null
Transform a single data object that can be null
Single data object that can be null
Transform an array wrapped in Maybe that can be undefined
Maybe-wrapped array that can be undefined
Transform an array of data objects
Array of data objects to transform
StaticpaginateCreate a paginated collection from an array of data with pagination metadata.
Array of data objects to transform into a paginated collection
Pagination metadata (e.g., page, perPage, total, etc.)
class UserTransformer extends BaseTransformer<User> {
toObject() {
return { id: this.resource.id, name: this.resource.name }
}
}
// Create paginated collection
const paginatedUsers = UserTransformer.paginate(
[user1, user2, user3],
{ page: 1, perPage: 10, total: 50 }
)
Wrap a value in a Maybe container to handle potentially undefined values. This is useful for relationships that may or may not be loaded.
The value to wrap in a Maybe container
class UserTransformer extends BaseTransformer<User> {
toObject() {
return {
id: this.resource.id,
profile: ProfileTransformer.transform(this.whenLoaded(this.resource.profile))
}
}
}
Conditionally compute a value based on a boolean condition. This is a cleaner alternative to using ternary operators in transformers.
Boolean condition to evaluate
Function that returns the value when condition is true
Optionalfallback: Fallback
Optional fallback value when condition is false (defaults to undefined)
class UserTransformer extends BaseTransformer<User> {
toObject() {
return {
id: this.resource.id,
name: this.resource.name,
// Include role only for admins
role: this.when(this.resource.role === 'admin', () => 'admin'),
// Include with fallback
status: this.when(this.resource.isActive, () => 'active', 'inactive')
}
}
}
Base class for creating custom data transformers. Provides utilities for transforming data into consistent API responses with support for relationships and conditional values.