Skip to content

Commit

Permalink
feat: add option to allow usage of custom parser (#121)
Browse files Browse the repository at this point in the history
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>
  • Loading branch information
MasterOdin authored and darrachequesne committed Jan 12, 2023
1 parent f26b810 commit 48bdd87
Show file tree
Hide file tree
Showing 6 changed files with 307 additions and 300 deletions.
1 change: 1 addition & 0 deletions Readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,7 @@ option set to `true`.
The following options are allowed:

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

### Emitter#to(room:String):BroadcastOperator
### Emitter#in(room:String):BroadcastOperator
Expand Down
14 changes: 13 additions & 1 deletion lib/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,17 +27,27 @@ enum RequestType {
SERVER_SIDE_EMIT = 6,
}

interface Parser {
encode: (msg: any) => any;
}

export interface EmitterOptions {
/**
* @default "socket.io"
*/
key?: string;
/**
* The parser to use for encoding messages sent to Redis.
* Defaults to notepack.io, a MessagePack implementation.
*/
parser?: Parser;
}

interface BroadcastOptions {
nsp: string;
broadcastChannel: string;
requestChannel: string;
parser: Parser;
}

interface BroadcastFlags {
Expand All @@ -57,13 +67,15 @@ export class Emitter<EmitEvents extends EventsMap = DefaultEventsMap> {
this.opts = Object.assign(
{
key: "socket.io",
parser: msgpack,
},
opts
);
this.broadcastOptions = {
nsp,
broadcastChannel: this.opts.key + "#" + nsp + "#",
requestChannel: this.opts.key + "-request#" + nsp + "#",
parser: this.opts.parser,
};
}

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

const msg = msgpack.encode([UID, packet, opts]);
const msg = this.broadcastOptions.parser.encode([UID, packet, opts]);
let channel = this.broadcastOptions.broadcastChannel;
if (this.rooms && this.rooms.size === 1) {
channel += this.rooms.keys().next().value + "#";
Expand Down
Loading

0 comments on commit 48bdd87

Please sign in to comment.