Skip to content

Commit

Permalink
fix(toJSON): Corrected serialisation of falsey primitives
Browse files Browse the repository at this point in the history
Thanks for spotting the issue, @Baasie!
  • Loading branch information
jan-molak committed Aug 29, 2018
1 parent 18b2000 commit 54179dc
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 2 deletions.
26 changes: 26 additions & 0 deletions spec/serialisation.spec.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,35 @@
import 'mocha';
import { given } from 'mocha-testdata';

import { Serialised, TinyType, TinyTypeOf } from '../src';
import { expect } from './expect';

describe('Serialisation', () => {

describe('of single-value TinyTypes', () => {

class Amount extends TinyTypeOf<number>() {}
class Name extends TinyTypeOf<string>() {}
class Vote extends TinyTypeOf<boolean>() {}
class Maybe extends TinyType {
constructor(public readonly value: any) {
super();
}
}

given([
{ obj: new Amount(0), expectedType: 'number' },
{ obj: new Amount(10/3), expectedType: 'number' },
{ obj: new Name('Jan'), expectedType: 'string' },
{ obj: new Vote(true), expectedType: 'boolean' },
{ obj: new Vote(false), expectedType: 'boolean' },
{ obj: new Maybe(undefined), expectedType: 'undefined' },
]).
it('preserves the type of the wrapped value', ({ obj, expectedType: expectedType }) => {
expect(obj.toJSON()).to.be.an(expectedType);
});
});

describe('of TinyTypes wrapping several primitive values', () => {

class Person extends TinyType {
Expand Down
6 changes: 4 additions & 2 deletions src/TinyType.ts
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,9 @@ export abstract class TinyType implements Serialisable {
toJSON(): JSONObject | NonNullJSONPrimitive {
const
isObject = (value: any) => Object(value) === value,
isPrimitive = (value: any) => Object(value) !== value;
isSerialisablePrimitive = (value: any) =>
!! ~ ['string', 'boolean', 'null', 'undefined'].indexOf(typeof value) ||
(typeof value === 'number' && ! isNaN(value) && ! ~ [ Infinity, -Infinity ].indexOf(value));

function toJSON(value: any): JSONObject | NonNullJSONPrimitive {
switch (true) {
Expand All @@ -134,7 +136,7 @@ export abstract class TinyType implements Serialisable {
return value.map(v => toJSON(v));
case value && isObject(value):
return JSON.parse(JSON.stringify(value));
case value && isPrimitive(value):
case isSerialisablePrimitive(value):
return value;
default:
return JSON.stringify(value);
Expand Down

0 comments on commit 54179dc

Please sign in to comment.