Skip to content

Commit

Permalink
fix: handle nil events / don't ignore internal phx events
Browse files Browse the repository at this point in the history
  • Loading branch information
s-r-x committed Apr 20, 2022
1 parent 4d848fa commit 4941436
Show file tree
Hide file tree
Showing 2 changed files with 3 additions and 25 deletions.
12 changes: 1 addition & 11 deletions src/index.spec.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Wildcard, INTERNAL_PHX_EVENTS, Glob } from './';
import { Wildcard, Glob } from './';
import { Channel } from 'phoenix';

const createChannelMock = () => {
Expand Down Expand Up @@ -70,16 +70,6 @@ it('should trigger subscribers on incoming events', () => {
expect(sub2.cb).toHaveBeenCalledWith(...args);
expect(sub3.cb).toHaveBeenCalledTimes(0);
});
it('should ignore internal phoenix events', () => {
const channel = createChannelMock();
const wildcard = new Wildcard(channel);
const sub = createSub('*');
wildcard.on(sub.glob, sub.cb);
[...Array.from(INTERNAL_PHX_EVENTS), 'event'].forEach(event => {
channel.onMessage(event, null, 1);
});
expect(sub.cb).toBeCalledTimes(1);
});
it('should call initial onMessage callback', () => {
const channel = createChannelMock();
const TRANSFORMED_PAYLOAD = 'new_payload';
Expand Down
16 changes: 2 additions & 14 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Channel } from 'phoenix';
import { isMatch } from 'matcher';
import type { Channel } from 'phoenix';

export type Glob = string | string[];
export type Callback = (event: string, payload: any, ref?: any) => any;
Expand All @@ -8,15 +8,6 @@ type Subscriber = {
cb: Callback;
};

export const INTERNAL_PHX_EVENTS = new Set([
'presence_diff',
'phx_close',
'phx_error',
'phx_join',
'phx_reply',
'phx_leave',
]);

export class Wildcard {
constructor(private _channel: Channel) {
if (!_channel) {
Expand Down Expand Up @@ -75,15 +66,12 @@ export class Wildcard {
throw new Error('This Wildcard instance is destroyed. Create a new one.');
}
}
private _isEventInternal(event: string) {
return INTERNAL_PHX_EVENTS.has(event) || event.startsWith('chan_reply');
}
private _onMessage = (event: string, payload: any, ref: any) => {
let finalPayload = payload;
if (this._initialOnMessageCallback) {
finalPayload = this._initialOnMessageCallback(event, payload, ref);
}
if (!this._isEventInternal(event)) {
if (event) {
this._subscribers.forEach(sub => {
if (isMatch(event, sub.glob)) {
sub.cb(event, finalPayload, ref);
Expand Down

0 comments on commit 4941436

Please sign in to comment.