Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add option to allow usage of custom parser #121

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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