Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commitb08bc1a

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

File tree

1 file changed

+22
-11
lines changed

1 file changed

+22
-11
lines changed

‎lib/index.ts

Lines changed: 22 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,12 @@ export interface Packet {
3636
*/
3737

3838
exportclassEncoder{
39+
/**
40+
* Encoder constructor
41+
*
42+
*@param {function} replacer - custom replacer to pass down to JSON.parse
43+
*/
44+
constructor(privatereplacer?:(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
exportclassDecoderextendsEmitter<{},{},DecoderReservedEvents>{
122128
privatereconstructor:BinaryReconstructor;
123129

124-
constructor(){
130+
/**
131+
* Decoder constructor
132+
*
133+
*@param {function} reviver - custom reviver to pass down to JSON.stringify
134+
*/
135+
constructor(privatereviver?:(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-
constpayload=tryParse(str.substr(i));
242+
constpayload=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
returnp;
241252
}
242253

254+
privatetryParse(str){
255+
try{
256+
returnJSON.parse(str,this.reviver);
257+
}catch(e){
258+
returnfalse;
259+
}
260+
}
261+
243262
privatestaticisPayloadValid(type:PacketType,payload:any):boolean{
244263
switch(type){
245264
casePacketType.CONNECT:
@@ -267,14 +286,6 @@ export class Decoder extends Emitter<{}, {}, DecoderReservedEvents> {
267286
}
268287
}
269288

270-
functiontryParse(str){
271-
try{
272-
returnJSON.parse(str);
273-
}catch(e){
274-
returnfalse;
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)

[8]ページ先頭

©2009-2025 Movatter.jp