Skip to content

Instantly share code, notes, and snippets.

@moein459
Created September 12, 2020 17:52
Show Gist options
  • Save moein459/4cbb250e4497d08b839173267f615363 to your computer and use it in GitHub Desktop.
Save moein459/4cbb250e4497d08b839173267f615363 to your computer and use it in GitHub Desktop.
import {Injectable} from '@angular/core';
import {HubConnection, HubConnectionBuilder, LogLevel} from '@microsoft/signalr';
import {environment} from '../../../environments/environment';
import {Deal, Offer} from 'core';
import {DealsStore} from '../../modules/room/modules/deal/state/deals.store';
import {Subject} from 'rxjs';
import {shareReplay, take} from 'rxjs/operators';
import {OffersStore} from "../../modules/room/modules/offer/state/offers.store";
import {ToastrService} from "ngx-toastr";
import {Room} from "../../modules/room/state/rooms.model";
import {RoomsStore} from "../../modules/room/state/rooms.store";
export enum GroupType {
Room = 0,
Deal = 1
}
@Injectable({
providedIn: 'root'
})
export class SocketService {
private connection: HubConnection;
private onStart = new Subject();
onStart$ = this.onStart.asObservable().pipe(shareReplay(1), take(1));
constructor(
private dealStore: DealsStore,
private offersStore: OffersStore,
private toastr: ToastrService,
private roomsStore: RoomsStore
) {
this.connection = new HubConnectionBuilder()
.withUrl(`${environment.APP_URL}hubs/events`)
.withAutomaticReconnect()
.configureLogging(LogLevel.Information)
.build();
}
start(): void {
this.connection.start().then(() => {
this.onStart.next();
});
this.connection.on('NewDeal', (deal: Deal) => {
this.dealStore.add(deal);
});
this.connection.on('NewDeal', (deal: Deal) => {
this.dealStore.add(deal);
});
this.connection.on('RejectDeal', (dealId: number) => {
this.dealStore.remove(dealId);
});
this.connection.on('CanceledDeal', (dealId: number) => {
this.dealStore.remove(dealId);
});
this.connection.on('NewOffer', (offer: Offer) => {
this.offersStore.add(offer);
});
this.connection.on('AcceptOffer', (offerId: number) => {
this.toastr.success('پیشنهاد شما تایید شد.');
});
this.connection.on('UpdateRoom', (room: Room) => {
this.roomsStore.update(room);
});
}
joinToRoom(roomId: number): void {
this.connection.invoke('JoinToGroup', GroupType.Room, roomId).then(() => console.log('joined'));
}
leftFromRoom(roomId: number): void {
this.connection.invoke('LeftFromGroup', GroupType.Room, roomId).then(() => console.log('left'));
}
joinToDeal(dealId: number): void {
this.connection.invoke('JoinToDeal', GroupType.Deal, dealId).then(() => console.log('joined'));
}
leftFromDeal(dealId: number): void {
this.connection.invoke('LeftFromDeal', GroupType.Deal, dealId).then(() => console.log('left'));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment