Skip to content

Commit

Permalink
Add support for Decimal data type
Browse files Browse the repository at this point in the history
Fixes flightcontrolhq#152

Add support for serialization of Decimal data type.

* **src/transformer.ts**
  - Import the Decimal class from the `decimal.js` library.
  - Add a transformation rule for the Decimal data type.
  - Update the `compositeRules` array to include the new Decimal transformation rule.

* **src/index.ts**
  - Register a custom transformer for the Decimal data type in the `SuperJSON` class constructor.

* **src/index.test.ts**
  - Update the test case for Decimal.js to use the built-in transformer.
  • Loading branch information
Royal-lobster committed Dec 30, 2024
1 parent 0ac86f0 commit 7311adc
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 10 deletions.
9 changes: 0 additions & 9 deletions src/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -523,15 +523,6 @@ describe('stringify & parse', () => {

'works for Decimal.js': {
input: () => {
SuperJSON.registerCustom<Decimal, string>(
{
isApplicable: (v): v is Decimal => Decimal.isDecimal(v),
serialize: v => v.toJSON(),
deserialize: v => new Decimal(v),
},
'decimal.js'
);

return {
a: new Decimal('100.1'),
};
Expand Down
10 changes: 10 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {
walker,
} from './plainer.js';
import { copy } from 'copy-anything';
import { Decimal } from 'decimal.js';

export default class SuperJSON {
/**
Expand All @@ -28,6 +29,15 @@ export default class SuperJSON {
dedupe?: boolean;
} = {}) {
this.dedupe = dedupe;

this.registerCustom<Decimal, string>(
{
isApplicable: (v): v is Decimal => Decimal.isDecimal(v),
serialize: v => v.toJSON(),
deserialize: v => new Decimal(v),
},
'decimal.js'
);
}

serialize(object: SuperJSONValue): SuperJSONResult {
Expand Down
10 changes: 9 additions & 1 deletion src/transformer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import {
} from './is.js';
import { findArr } from './util.js';
import SuperJSON from './index.js';
import { Decimal } from 'decimal.js';

export type PrimitiveTypeAnnotation = 'number' | 'undefined' | 'bigint';

Expand Down Expand Up @@ -308,7 +309,14 @@ const customRule = compositeTransformation(
}
);

const compositeRules = [classRule, symbolRule, customRule, typedArrayRule];
const decimalRule = compositeTransformation(
(value): value is Decimal => Decimal.isDecimal(value),
() => ['custom', 'decimal.js'],
(value) => value.toJSON(),
(value) => new Decimal(value)
);

const compositeRules = [classRule, symbolRule, customRule, typedArrayRule, decimalRule];

export const transformValue = (
value: any,
Expand Down

0 comments on commit 7311adc

Please sign in to comment.