From 7311adc0235cacc064a7d92f1bf8ffd943d58dc3 Mon Sep 17 00:00:00 2001 From: Srujan Gurram <52039218+Royal-lobster@users.noreply.github.com> Date: Mon, 30 Dec 2024 10:33:59 +0530 Subject: [PATCH] Add support for Decimal data type Fixes #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. --- src/index.test.ts | 9 --------- src/index.ts | 10 ++++++++++ src/transformer.ts | 10 +++++++++- 3 files changed, 19 insertions(+), 10 deletions(-) diff --git a/src/index.test.ts b/src/index.test.ts index 3ef96a1..568cc56 100644 --- a/src/index.test.ts +++ b/src/index.test.ts @@ -523,15 +523,6 @@ describe('stringify & parse', () => { 'works for Decimal.js': { input: () => { - SuperJSON.registerCustom( - { - 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'), }; diff --git a/src/index.ts b/src/index.ts index 5636e65..e0b0ee4 100644 --- a/src/index.ts +++ b/src/index.ts @@ -12,6 +12,7 @@ import { walker, } from './plainer.js'; import { copy } from 'copy-anything'; +import { Decimal } from 'decimal.js'; export default class SuperJSON { /** @@ -28,6 +29,15 @@ export default class SuperJSON { dedupe?: boolean; } = {}) { this.dedupe = dedupe; + + this.registerCustom( + { + isApplicable: (v): v is Decimal => Decimal.isDecimal(v), + serialize: v => v.toJSON(), + deserialize: v => new Decimal(v), + }, + 'decimal.js' + ); } serialize(object: SuperJSONValue): SuperJSONResult { diff --git a/src/transformer.ts b/src/transformer.ts index 7bbb1bc..97e6835 100644 --- a/src/transformer.ts +++ b/src/transformer.ts @@ -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'; @@ -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,