Skip to content

Commit

Permalink
feat(*): add RedisHub for Redis support with sseHub()
Browse files Browse the repository at this point in the history
  • Loading branch information
toverux committed Aug 18, 2017
1 parent bb4996e commit 0882759
Show file tree
Hide file tree
Showing 4 changed files with 335 additions and 6 deletions.
6 changes: 5 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@
"@types/mocha": "^2.2.41",
"@types/node": "^8.0.13",
"chai": "^4.0.0",
"cors": "^2.8.4",
"express": "^4.15.4",
"mocha": "^3.4.2",
"semantic-release": "^6.3.6",
"tslint": "^5.2.0",
Expand All @@ -36,6 +38,8 @@
"express": ">=4.0.0"
},
"dependencies": {
"compose-middleware": "^2.2.0"
"@types/ioredis": "^0.0.24",
"compose-middleware": "^2.2.0",
"ioredis": "^3.1.1"
}
}
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
export * from './hub';
export * from './redis_hub';
export { ISseMiddlewareOptions } from './sse_handler_middleware';
export * from './sse_middleware';
export * from './sse_hub_middleware';
Expand Down
48 changes: 48 additions & 0 deletions src/redis_hub.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import * as Redis from 'ioredis';
import { Hub } from './hub';
import * as fmt from './sse_formatter';
import { ISseFunctions } from './sse_middleware';

interface ISerializedSseMessage {
type: keyof ISseFunctions;
args: any[];
}

export class RedisHub extends Hub {
public constructor(
public readonly channel: string,
private readonly pub = new Redis(),
private readonly sub = new Redis()
) {
super();

sub.subscribe(channel);
sub.on('message', (chan, message) => this.handleRedisMessage(message));
}

public data(data: fmt.SseValue, id?: string): void {
this.publish('data', arguments);
}

public event(event: string, data: fmt.SseValue, id?: string): void {
this.publish('event', arguments);
}

public comment(comment: string): void {
this.publish('comment', arguments);
}

private publish(type: keyof ISseFunctions, args: IArguments): void {
const message: ISerializedSseMessage = {
type, args: Array.from(args)
};

this.pub.publish(this.channel, JSON.stringify(message));
}

private handleRedisMessage(jsonMessage: string): void {
const { type, args } = JSON.parse(jsonMessage) as ISerializedSseMessage;

super[type].apply(this, args);
}
}
Loading

0 comments on commit 0882759

Please sign in to comment.