Skip to content

Transform Decorator

This file defines the Transform decorator for the @sodacore/core HTTP module. It allows you to attach transformer functions to controllers or controller methods, enabling you to modify or process the response data before it is sent to the client.


Features

  • Response Transformation: Attach one or more transformer functions to a controller or method to modify the response data.
  • Flexible Scope: Apply transformers globally to an entire controller or to specific methods.
  • Context-Aware: Transformer functions receive both the HttpContext and the response data, allowing for context-sensitive transformations.
  • Supports Async: Transformer functions can be synchronous or return a promise.

Usage

typescript
import Transform from './decorator/transform';

@Transform((context, response) => {
	// Global transformation for all methods in this controller
	return { ...response, transformed: true };
})
class MyController {
	@Transform((context, response) => {
		// Method-specific transformation
		return { ...response, methodTransformed: true };
	})
	async myMethod() {
		return { data: 'original' };
	}
}

API

Transform(func: (context: HttpContext, response: any) => MaybePromise<any>): ClassDecorator & MethodDecorator

  • func: A function that receives the HTTP context and the response data, and returns the transformed data (either synchronously or as a promise).
  • Returns: A decorator that can be applied to a class or a method.

How It Works

  • When applied, the decorator stores the transformer function(s) in the controller or method's metadata.
  • When a controller method returns data, all attached transformers are executed in order, allowing each to modify the response.
  • Transformers can be chained, and each receives the output of the previous transformer.

Notes

  • Transformers are useful for tasks such as localization, formatting, filtering, or any custom response processing.
  • Multiple transformers can be attached; they will be executed in the order they were added.
  • This decorator is intended for use with HTTP controllers and methods in the Sodacore framework.

Released under the Apache-2.0 License.