Skip to content

Commit

Permalink
fix(core): improve support for mapping DecimalType to number
Browse files Browse the repository at this point in the history
  • Loading branch information
B4nan committed May 2, 2024
1 parent e513cb9 commit 5a3e30e
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 2 deletions.
12 changes: 12 additions & 0 deletions docs/docs/custom-types.md
Original file line number Diff line number Diff line change
Expand Up @@ -383,6 +383,18 @@ id3: number;

> JavaScript cannot represent all the possible values of a `bigint` when mapping to the `number` type - only values up to `Number.MAX_SAFE_INTEGER` (2^53 - 1) are safely supported.
### DecimalType

DecimalType represents a `decimal` or `numeric` column type. By default, it maps to a JS `string`, as mapping it to `number` could result is precision lost. If you are fine with that, you can force mapping to a `number` with its constructor (just like with the `BigIntType`).

```ts
@Property({ type: DecimalType })
price1: string;

@PrimaryKey({ type: new DecimalType('number') })
price2: number;
```

### BlobType

Blob type can be used to store binary data in the database.
Expand Down
8 changes: 6 additions & 2 deletions packages/core/src/types/DecimalType.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,12 @@ import type { EntityProperty } from '../typings';
*/
export class DecimalType extends Type<string | number, string> {

constructor(public mode?: 'number' | 'string') {
super();
}

override convertToJSValue(value: string): number | string {
if (this.prop?.runtimeType === 'number') {
if ((this.mode ?? this.prop?.runtimeType) === 'number') {
return +value;
}

Expand All @@ -20,7 +24,7 @@ export class DecimalType extends Type<string | number, string> {
}

override compareAsType(): string {
return this.prop?.runtimeType ?? 'string';
return this.mode ?? this.prop?.runtimeType ?? 'string';
}

}

0 comments on commit 5a3e30e

Please sign in to comment.