Skip to content

Commit 48bdd87

Browse files
MasterOdindarrachequesne
authored andcommitted
feat: add option to allow usage of custom parser (#121)
This PR adds a new parser option to the adapter constructor to allow setting a custom parser to use, defaulting to using notepack.io. This would allow someone to use a different msgpack library if they wanted, or even an entirely different protocol altogether (e.g. protobuf). Related: socketio/socket.io-redis-adapter@73f6320 Signed-off-by: Matthew Peveler <matt@popsql.com>
1 parent f26b810 commit 48bdd87

File tree

6 files changed

+307
-300
lines changed

6 files changed

+307
-300
lines changed

Readme.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -161,6 +161,7 @@ option set to `true`.
161161
The following options are allowed:
162162

163163
- `key`: the name of the key to pub/sub events on as prefix (`socket.io`)
164+
- `parser`: parser to use for encoding messages to Redis ([`notepack.io](https://www.npmjs.com/package/notepack.io))
164165

165166
### Emitter#to(room:String):BroadcastOperator
166167
### Emitter#in(room:String):BroadcastOperator

lib/index.ts

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,17 +27,27 @@ enum RequestType {
2727
SERVER_SIDE_EMIT = 6,
2828
}
2929

30+
interface Parser {
31+
encode: (msg: any) => any;
32+
}
33+
3034
export interface EmitterOptions {
3135
/**
3236
* @default "socket.io"
3337
*/
3438
key?: string;
39+
/**
40+
* The parser to use for encoding messages sent to Redis.
41+
* Defaults to notepack.io, a MessagePack implementation.
42+
*/
43+
parser?: Parser;
3544
}
3645

3746
interface BroadcastOptions {
3847
nsp: string;
3948
broadcastChannel: string;
4049
requestChannel: string;
50+
parser: Parser;
4151
}
4252

4353
interface BroadcastFlags {
@@ -57,13 +67,15 @@ export class Emitter<EmitEvents extends EventsMap = DefaultEventsMap> {
5767
this.opts = Object.assign(
5868
{
5969
key: "socket.io",
70+
parser: msgpack,
6071
},
6172
opts
6273
);
6374
this.broadcastOptions = {
6475
nsp,
6576
broadcastChannel: this.opts.key + "#" + nsp + "#",
6677
requestChannel: this.opts.key + "-request#" + nsp + "#",
78+
parser: this.opts.parser,
6779
};
6880
}
6981

@@ -366,7 +378,7 @@ export class BroadcastOperator<EmitEvents extends EventsMap>
366378
except: [...this.exceptRooms],
367379
};
368380

369-
const msg = msgpack.encode([UID, packet, opts]);
381+
const msg = this.broadcastOptions.parser.encode([UID, packet, opts]);
370382
let channel = this.broadcastOptions.broadcastChannel;
371383
if (this.rooms && this.rooms.size === 1) {
372384
channel += this.rooms.keys().next().value + "#";

0 commit comments

Comments
 (0)