I have some columns with type decimal. I am using query builder for aggregation. The only problem is after aggregating the result the fields that have decimal values are returning as string after executing the query.
I want to set it globally across my project to consider decimal numbers in entity as decimal numbers only while executing queries and not string.
I have tried using transformer with @Column() but it is not working.
@Column('decimal', {
transformer: {
to(value) {
return value;
},
from(value) {
return parseFloat(value);
},
},
})
price: number;
but even if it works I don't want to write same thing for all columns. I want to make this setting globally.
This is known safeguard in postgresql, because aggregate operations can result in values that can fall outside the range of number
type in JavaScript. Hence as a safety, these values are returned as string
.
A similar safeguard exists in mysql
as well (which can be handled using supportBigNumbers: false
setting in node-mysql
package).
You can create a NestJS transformer (like below) and then reuse it in your entities. You can adjust the precision
and scale
to suite your needs.
// transformer
export class DecimalColumnTransformer {
to(data: number): number {
return data;
}
from(data: string): number {
return parseFloat(data);
}
}
// entity
@Column('decimal', {
precision: 5,
scale: 2,
transformer: new DecimalColumnTransformer(),
})
price: number;