Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for Decimal data type #308

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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