Skip to content

Commit 822816b

Browse files
committed
feat: allow the usage of custom replacer and reviver
1 parent ea86f41 commit 822816b

File tree

1 file changed

+23
-11
lines changed

1 file changed

+23
-11
lines changed

lib/index.ts

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

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

8794
// json data
8895
if (null != obj.data) {
89-
str += JSON.stringify(obj.data);
96+
str += JSON.stringify(obj.data, this.replacer);
9097
}
9198

9299
debug("encoded %j as %s", obj, str);
@@ -121,7 +128,12 @@ interface DecoderReservedEvents {
121128
export class Decoder extends Emitter<{}, {}, DecoderReservedEvents> {
122129
private reconstructor: BinaryReconstructor;
123130

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

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

229241
// look up json data
230242
if (str.charAt(++i)) {
231-
const payload = tryParse(str.substr(i));
243+
const payload = this.tryParse(str.substr(i));
232244
if (Decoder.isPayloadValid(p.type, payload)) {
233245
p.data = payload;
234246
} else {
@@ -240,6 +252,14 @@ export class Decoder extends Emitter<{}, {}, DecoderReservedEvents> {
240252
return p;
241253
}
242254

255+
private tryParse(str) {
256+
try {
257+
return JSON.parse(str, this.reviver);
258+
} catch (e) {
259+
return false;
260+
}
261+
}
262+
243263
private static isPayloadValid(type: PacketType, payload: any): boolean {
244264
switch (type) {
245265
case PacketType.CONNECT:
@@ -267,14 +287,6 @@ export class Decoder extends Emitter<{}, {}, DecoderReservedEvents> {
267287
}
268288
}
269289

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

0 commit comments

Comments
 (0)