Skip to content

Commit b08bc1a

Browse files
bytenikcmocanu
andauthored
feat: allow the usage of custom replacer and reviver (#112)
Co-authored-by: Mocanu Cristian <mocanu.cristian93@gmail.com>
1 parent aed252c commit b08bc1a

File tree

1 file changed

+22
-11
lines changed

1 file changed

+22
-11
lines changed

lib/index.ts

+22-11
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,12 @@ export interface Packet {
3636
*/
3737

3838
export class Encoder {
39+
/**
40+
* Encoder constructor
41+
*
42+
* @param {function} replacer - custom replacer to pass down to JSON.parse
43+
*/
44+
constructor(private replacer?: (this: any, key: string, value: any) => any) {}
3945
/**
4046
* Encode a packet as a single string if non-binary, or as a
4147
* buffer sequence, depending on packet type.
@@ -86,7 +92,7 @@ export class Encoder {
8692

8793
// json data
8894
if (null != obj.data) {
89-
str += JSON.stringify(obj.data);
95+
str += JSON.stringify(obj.data, this.replacer);
9096
}
9197

9298
debug("encoded %j as %s", obj, str);
@@ -121,7 +127,12 @@ interface DecoderReservedEvents {
121127
export class Decoder extends Emitter<{}, {}, DecoderReservedEvents> {
122128
private reconstructor: BinaryReconstructor;
123129

124-
constructor() {
130+
/**
131+
* Decoder constructor
132+
*
133+
* @param {function} reviver - custom reviver to pass down to JSON.stringify
134+
*/
135+
constructor(private reviver?: (this: any, key: string, value: any) => any) {
125136
super();
126137
}
127138

@@ -228,7 +239,7 @@ export class Decoder extends Emitter<{}, {}, DecoderReservedEvents> {
228239

229240
// look up json data
230241
if (str.charAt(++i)) {
231-
const payload = tryParse(str.substr(i));
242+
const payload = this.tryParse(str.substr(i));
232243
if (Decoder.isPayloadValid(p.type, payload)) {
233244
p.data = payload;
234245
} else {
@@ -240,6 +251,14 @@ export class Decoder extends Emitter<{}, {}, DecoderReservedEvents> {
240251
return p;
241252
}
242253

254+
private tryParse(str) {
255+
try {
256+
return JSON.parse(str, this.reviver);
257+
} catch (e) {
258+
return false;
259+
}
260+
}
261+
243262
private static isPayloadValid(type: PacketType, payload: any): boolean {
244263
switch (type) {
245264
case PacketType.CONNECT:
@@ -267,14 +286,6 @@ export class Decoder extends Emitter<{}, {}, DecoderReservedEvents> {
267286
}
268287
}
269288

270-
function tryParse(str) {
271-
try {
272-
return JSON.parse(str);
273-
} catch (e) {
274-
return false;
275-
}
276-
}
277-
278289
/**
279290
* A manager of a binary event's 'buffer sequence'. Should
280291
* be constructed whenever a packet of type BINARY_EVENT is

0 commit comments

Comments
 (0)