Skip to content

Commit

Permalink
added support for custom reviver in JSONCodec (#242)
Browse files Browse the repository at this point in the history
  • Loading branch information
tommyo committed Jan 18, 2022
1 parent b5642ac commit c3c9711
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 2 deletions.
4 changes: 2 additions & 2 deletions nats-base-client/codec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ export function StringCodec(): Codec<string> {
};
}

export function JSONCodec<T = unknown>(): Codec<T> {
export function JSONCodec<T = unknown>(reviver? :(this: any, key: string, value: any) => any): Codec<T> {
return {
encode(d: T): Uint8Array {
try {
Expand All @@ -48,7 +48,7 @@ export function JSONCodec<T = unknown>(): Codec<T> {

decode(a: Uint8Array): T {
try {
return JSON.parse(TD.decode(a));
return JSON.parse(TD.decode(a), reviver);
} catch (err) {
throw NatsError.errorForCode(ErrorCode.BadJson, err);
}
Expand Down
7 changes: 7 additions & 0 deletions tests/codec_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,3 +27,10 @@ Deno.test("codec - json", () => {
const d = sc.encode(o);
assertEquals(sc.decode(d), o);
});

Deno.test("codec - json w/ reviver", () => {
const sc = JSONCodec((k: string, v: any) => k === "time" ? new Date(v) : v);
const o = { time: new Date() };
const d = sc.encode(o);
assertEquals(sc.decode(d), o);
});

0 comments on commit c3c9711

Please sign in to comment.