Skip to content
Merged
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
9 changes: 6 additions & 3 deletions src/echo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import {
SocketIoPrivateChannel,
} from './channel';
import { Connector, PusherConnector, SocketIoConnector, NullConnector } from './connector';
import { isConstructor } from './util';

/**
* This class is the primary API for interacting with broadcasting.
Expand Down Expand Up @@ -60,8 +61,8 @@ export default class Echo<T extends keyof Broadcaster> {
this.connector = new SocketIoConnector(this.options);
} else if (this.options.broadcaster == 'null') {
this.connector = new NullConnector(this.options);
} else if (typeof this.options.broadcaster == 'function') {
this.connector = this.options.broadcaster(this.options as EchoOptions<'function'>);
} else if (typeof this.options.broadcaster == 'function' && isConstructor(this.options.broadcaster)) {
this.connector = new this.options.broadcaster(this.options as EchoOptions<'function'>);
} else {
throw new Error(
`Broadcaster ${typeof this.options.broadcaster} ${this.options.broadcaster} is not supported.`
Expand Down Expand Up @@ -261,11 +262,13 @@ type Broadcaster = {
};
};

type Constructor<T = {}> = new (...args: any[]) => T;

type EchoOptions<T extends keyof Broadcaster> = {
/**
* The broadcast connector.
*/
broadcaster: T extends 'function' ? (options: EchoOptions<T>) => any : T;
broadcaster: T extends 'function' ? Constructor<InstanceType<Broadcaster[T]['connector']>> : T;

[key: string]: any;
};
10 changes: 10 additions & 0 deletions src/util/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1,11 @@
function isConstructor(obj: any): obj is new (...args: any[]) => any {
try {
new obj();
} catch (err) {
if (err.message.includes('is not a constructor')) return false;
}
return true;
}

export { isConstructor };
export * from './event-formatter';
4 changes: 4 additions & 0 deletions tests/echo.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import Echo from '../src/echo';
import { NullConnector } from '../src/connector';

describe('Echo', () => {
test('it will not throw error for supported driver', () => {
Expand All @@ -15,7 +16,10 @@ describe('Echo', () => {
);

expect(() => new Echo({ broadcaster: 'null' })).not.toThrowError('Broadcaster string null is not supported.');
expect(() => new Echo({ broadcaster: NullConnector })).not.toThrowError();

// eslint-disable-next-line
// @ts-ignore
// eslint-disable-next-line @typescript-eslint/no-empty-function
expect(() => new Echo({ broadcaster: () => {} })).not.toThrowError('Broadcaster function is not supported.');
});
Expand Down
Loading