@atton16/ngx-socket-io
Version:
Socket.IO module for Angular
105 lines (100 loc) • 3.34 kB
JavaScript
import { InjectionToken, NgModule } from '@angular/core';
import { Observable } from 'rxjs';
import { share } from 'rxjs/operators';
import * as io from 'socket.io-client';
import io__default from 'socket.io-client';
class WrappedSocket {
constructor(config) {
this.config = config;
this.subscribersCounter = {};
this.eventObservables$ = {};
this.emptyConfig = {
url: '',
options: {}
};
if (config === undefined) {
config = this.emptyConfig;
}
const url = config.url;
const options = config.options;
const ioFunc = io__default ? io__default : io;
this.ioSocket = ioFunc(url, options);
}
of(namespace) {
this.ioSocket.of(namespace);
}
on(eventName, callback) {
this.ioSocket.on(eventName, callback);
}
once(eventName, callback) {
this.ioSocket.once(eventName, callback);
}
connect() {
return this.ioSocket.connect();
}
disconnect(close) {
return this.ioSocket.disconnect.apply(this.ioSocket, arguments);
}
emit(eventName, ...args) {
return this.ioSocket.emit.apply(this.ioSocket, arguments);
}
removeListener(eventName, callback) {
return this.ioSocket.removeListener.apply(this.ioSocket, arguments);
}
removeAllListeners(eventName) {
return this.ioSocket.removeAllListeners.apply(this.ioSocket, arguments);
}
fromEvent(eventName) {
if (!this.subscribersCounter[eventName]) {
this.subscribersCounter[eventName] = 0;
}
this.subscribersCounter[eventName]++;
if (!this.eventObservables$[eventName]) {
this.eventObservables$[eventName] = new Observable((observer) => {
const listener = (data) => {
observer.next(data);
};
this.ioSocket.on(eventName, listener);
return () => {
this.subscribersCounter[eventName]--;
if (this.subscribersCounter[eventName] === 0) {
this.ioSocket.removeListener(eventName, listener);
delete this.eventObservables$[eventName];
}
};
}).pipe(share());
}
return this.eventObservables$[eventName];
}
fromOneTimeEvent(eventName) {
return new Promise(resolve => this.once(eventName, resolve));
}
}
/** Socket factory */
function SocketFactory(config) {
return new WrappedSocket(config);
}
const SOCKET_CONFIG_TOKEN = new InjectionToken('__SOCKET_IO_CONFIG__');
class SocketIoModule {
static forRoot(config) {
return {
ngModule: SocketIoModule,
providers: [
{ provide: SOCKET_CONFIG_TOKEN, useValue: config },
{
provide: WrappedSocket,
useFactory: SocketFactory,
deps: [SOCKET_CONFIG_TOKEN]
}
]
};
}
}
SocketIoModule.decorators = [
{ type: NgModule, args: [{},] }
];
/**
* Generated bundle index. Do not edit.
*/
export { WrappedSocket as Socket, SocketIoModule, SocketFactory as ɵa, SOCKET_CONFIG_TOKEN as ɵb };
//# sourceMappingURL=atton16-ngx-socket-io.js.map