From b08bc1a93e8e3194b776c8a0bdedee1e29333680 Mon Sep 17 00:00:00 2001 From: David Pfeffer Date: Sun, 17 Apr 2022 18:19:02 -0400 Subject: [PATCH] feat: allow the usage of custom replacer and reviver (#112) Co-authored-by: Mocanu Cristian --- lib/index.ts | 33 ++++++++++++++++++++++----------- 1 file changed, 22 insertions(+), 11 deletions(-) diff --git a/lib/index.ts b/lib/index.ts index 133df63..453425f 100644 --- a/lib/index.ts +++ b/lib/index.ts @@ -36,6 +36,12 @@ export interface Packet { */ export class Encoder { + /** + * Encoder constructor + * + * @param {function} replacer - custom replacer to pass down to JSON.parse + */ + constructor(private replacer?: (this: any, key: string, value: any) => any) {} /** * Encode a packet as a single string if non-binary, or as a * buffer sequence, depending on packet type. @@ -86,7 +92,7 @@ export class Encoder { // json data if (null != obj.data) { - str += JSON.stringify(obj.data); + str += JSON.stringify(obj.data, this.replacer); } debug("encoded %j as %s", obj, str); @@ -121,7 +127,12 @@ interface DecoderReservedEvents { export class Decoder extends Emitter<{}, {}, DecoderReservedEvents> { private reconstructor: BinaryReconstructor; - constructor() { + /** + * Decoder constructor + * + * @param {function} reviver - custom reviver to pass down to JSON.stringify + */ + constructor(private reviver?: (this: any, key: string, value: any) => any) { super(); } @@ -228,7 +239,7 @@ export class Decoder extends Emitter<{}, {}, DecoderReservedEvents> { // look up json data if (str.charAt(++i)) { - const payload = tryParse(str.substr(i)); + const payload = this.tryParse(str.substr(i)); if (Decoder.isPayloadValid(p.type, payload)) { p.data = payload; } else { @@ -240,6 +251,14 @@ export class Decoder extends Emitter<{}, {}, DecoderReservedEvents> { return p; } + private tryParse(str) { + try { + return JSON.parse(str, this.reviver); + } catch (e) { + return false; + } + } + private static isPayloadValid(type: PacketType, payload: any): boolean { switch (type) { case PacketType.CONNECT: @@ -267,14 +286,6 @@ export class Decoder extends Emitter<{}, {}, DecoderReservedEvents> { } } -function tryParse(str) { - try { - return JSON.parse(str); - } catch (e) { - return false; - } -} - /** * A manager of a binary event's 'buffer sequence'. Should * be constructed whenever a packet of type BINARY_EVENT is