Transformers
Transformers are essentially functions that can accept an input and return a transformed output, they are useful for transforming data between different formats, or potentially sanitising data before it's sent to a client.
Usage
In short, there are a wide range of uses, in the Sodacore framework there is only one transformer called TranslateTransformer
and is provided by the @sodacore/i18n
package, this transformer is used to translate strings using the i18n service. The transformer is used to take accept data, either anything (but a Response) and then will attempt to run any translations it finds within the data, returning the translated data.
Transformers have to be applied to a controller or method using the @Transform
decorator, like so:
import { Controller, Get, HttpContext } from '@sodacore/http';
const reverseTransformer = (ctx: HttpContext, response: any) => {
if (typeof response === 'string') {
return response.split('').reverse().join('');
} else {
return response;
}
};
@Controller('/transform')
export class TransformController {
@Get('/reverse')
@Transform(reverseTransformer)
public async reverseString(@Body() body: { text: string }) {
return body.text;
}
}
As you can see, we simply define a function to reverse a string, if it's a string, we then apply the @Transform
decorator to the method, passing in our transformer function, and then when we return a string from the method, it will be reversed by the transformer before being sent to the client.
If a request responds with a string, you can always clone the request, or override the responding request, it still lives within the same request lifecycle and therefore returning a null, can be transformed to a 404 response, etc...