Skip to content

Commit

Permalink
feat(serialize): add generic type and typeGuard parameter to serializ…
Browse files Browse the repository at this point in the history
…e and deserialize
  • Loading branch information
Kit-p committed Jul 17, 2023
1 parent 33dd7ba commit 6542bf6
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 4 deletions.
9 changes: 7 additions & 2 deletions src/serialize.ts
Original file line number Diff line number Diff line change
@@ -1,32 +1,37 @@
import { parse } from './parse.js';
import { stringify } from './stringify.js';
import type { TypeGuardFunction } from './types.js';

export function serialize(obj: any) {
export function serialize<T>(obj: any, typeGuard?: TypeGuardFunction<T>) {
return parse(
stringify(obj, {
extended: { enable: true, relaxed: true },
compress: { enable: false },
minify: { enable: false },
}),
null,
{
extended: { enable: false },
decompress: { enable: false },
unminify: { enable: false },
},
typeGuard,
);
}

export function deserialize(obj: any) {
export function deserialize<T>(obj: any, typeGuard?: TypeGuardFunction<T>) {
return parse(
stringify(obj, {
extended: { enable: false },
compress: { enable: false },
minify: { enable: false },
}),
null,
{
extended: { enable: true, relaxed: true },
decompress: { enable: false },
unminify: { enable: false },
},
typeGuard,
);
}
4 changes: 2 additions & 2 deletions test/serialize.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ describe('[serialize] serialize', () => {
};

it('serialize should transform JavaScript object into Extended JSON object', () => {
const serializedObj = JsonKit.serialize(obj);
const serializedObj = JsonKit.serialize<{ date: unknown }>(obj);
expect(serializedObj.date).toHaveProperty('$date');
});
});
Expand All @@ -18,7 +18,7 @@ describe('[serialize] deserialize', () => {
};

it('deserialize should transform Extended JSON object into JavaScript object', () => {
const deserializedObj = JsonKit.deserialize(obj);
const deserializedObj = JsonKit.deserialize<{ date: unknown }>(obj);
expect(deserializedObj.date).toBeInstanceOf(Date);
});
});

0 comments on commit 6542bf6

Please sign in to comment.