I want to create functionality where I can transform incoming data before it hits the database. Let's say that we want to make sure that when a new user is created, the firstName and lastName attribute values are always starting with a capital letter. Or another great example is to prevent login issues and store email addresses always in lowercase letters.
I've taken a look at the pipe documentation of NestJS but it's too generic. I want to be able to specify which fields need transformation and I don't want to create a pipe for each attribute or endpoint that needs transformation.
I've also tried the @Transform decorator form the 'class-transformer' package but this doesn't seem to work.
export class UserRoleCreateDto {
@IsDefined()
@IsString()
@IsNotEmpty()
@Transform((name) => name.toUpperCase())
readonly name;
}
The expected result should be the name in uppercase letters but it's not.
Anyone any ideas or examples on how to implement proper input transformation for NestJS / TypeORM before it hits the database?
Thanks for your time!
With its rich feature set and flexibility, TypeORM is one of the best ORMs for NestJS.
Serialization is a process that happens before objects are returned in a network response. This is an appropriate place to provide rules for transforming and sanitizing the data to be returned to the client.
TypeORM is a TypeScript ORM (object-relational mapper) library that makes it easy to link your TypeScript application up to a relational database database. TypeORM supports MySQL, SQlite, Postgres, MS SQL Server, and a host of other traditional options.
Repositories are classes or components that encapsulate the logic required to access data sources. They centralize common data access functionality, providing better maintainability and decoupling the infrastructure or technology used to access databases from the domain model layer. —
Here is a small working example
@UsePipes(new ValidationPipe({transform: true}))
@Get('test_input')
async testInput(@Query() data: UserRoleCreateDto): Promise<any> {
return data;
}
and checking in bash:
curl 'http://localhost:3060/test_input?name=hello'
{"name":"HELLO"}
Check that you have ValidationPipe
decorator and especially transform: true
option, without these it doesn't work. transform: true
automatically transforms input data to the class instance.
More about validation on the nestjs documentation page - link
Also, just in case, instead of @Query()
decorator you can use @Body()
for POST data or @Param()
for URL parameters
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With