Skip to content

Commit

Permalink
feat: allow the usage of custom replacer and reviver
Browse files Browse the repository at this point in the history
  • Loading branch information
cmocanu committed Jan 20, 2022
1 parent ea86f41 commit 822816b
Showing 1 changed file with 23 additions and 11 deletions.
34 changes: 23 additions & 11 deletions lib/index.ts
Expand Up @@ -36,6 +36,13 @@ 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.
Expand Down Expand Up @@ -86,7 +93,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);
Expand Down Expand Up @@ -121,7 +128,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();
}

Expand Down Expand Up @@ -228,7 +240,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 {
Expand All @@ -240,6 +252,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:
Expand Down Expand Up @@ -267,14 +287,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
Expand Down

0 comments on commit 822816b

Please sign in to comment.