All files / src owservable.client.ts

5.61% Statements 5/89
0% Branches 0/32
0% Functions 0/19
6.17% Lines 5/81

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187      1x 1x     1x   1x       1x                                                                                                                                                                                                                                                                                                                                                          
'use strict';
 
import Timeout = NodeJS.Timeout;
import {get, includes, join} from 'lodash';
import {Subject, Subscription} from 'rxjs';
 
import AStore from './store/a.store';
import storeFactory from './store/factories/store.factory';
import IConnectionManager from './auth/i.connection.manager';
import DataMiddlewareMap from './middleware/data.middleware.map';
import StoreSubscriptionUpdateType from './_types/store.subscription.update.type';
import ConnectionManagerRefreshType from './_types/connection.manager.refresh.type';
 
export default class OwservableClient extends Subject<any> {
	private readonly _connectionManager: IConnectionManager;
 
	private _ping: number = 0;
	private _location: string;
	private _stores: Map<string, AStore>;
	private _subscriptions: Map<string, Subscription>;
	private _timeout: Timeout;
 
	public constructor(connectionManager: IConnectionManager) {
		super();
		this._connectionManager = connectionManager;
		this._stores = new Map<string, AStore>();
		this._subscriptions = new Map<string, Subscription>();
	}
 
	public disconnected(): void {
		// console.log('[@owservable] -> OwservableClient disconnected');
		this.clearSubscriptions();
		this._connectionManager.disconnected();
		clearTimeout(this._timeout);
	}
 
	private set location(location: string) {
		// console.log('[@owservable] -> OwservableClient location: old:[${this._location}] new:[${location}]`);
		Iif (location === this._location) return;
		this._location = location;
 
		this._connectionManager.location(location);
	}
 
	public async consume(message: any): Promise<void> {
		// console.log('[@owservable] -> OwservableClient::consume received message", message.type);
 
		switch (message.type) {
			case 'pong':
				return this._processPong(message);
 
			case 'authenticate':
				this._connectionManager.connected(message.jwt);
				return this._checkSession();
 
			case 'location': {
				const {path} = message;
				this.location = path;
				return;
			}
 
			case 'subscribe':
				return this.updateSubscription(message);
 
			case 'unsubscribe':
				return this.removeSubscription(message.target);
 
			case 'reload':
				return this.reloadData(message.target);
		}
	}
 
	public ping(): void {
		this.next({type: 'ping', id: new Date().getTime()});
		setTimeout(() => this.ping(), 60000);
	}
 
	private _processPong(message: any): void {
		const response: number = new Date().getTime();
		this._ping = response - message.id;
		this._connectionManager.ping(this._ping);
	}
 
	private async _checkSession(): Promise<void> {
		const check: ConnectionManagerRefreshType = await this._connectionManager.checkSession();
		Iif (check) this.next(check);
 
		let refreshIn: number = get(check, 'refresh_in', 300000); // 300000 = 5min
		refreshIn = Math.round((refreshIn * 95) / 100);
 
		clearTimeout(this._timeout);
		this._timeout = setTimeout(() => this._checkSession(), refreshIn);
	}
 
	private removeSubscription(target: string): void {
		// console.log('[@owservable] -> OwservableClient removeSubscription: ${target}`);
 
		this._subscriptions.get(target)?.unsubscribe();
		this._subscriptions.delete(target);
 
		this._stores.get(target)?.destroy();
		this._stores.delete(target);
 
		this.sendDebugTargets('removeSubscription', target);
	}
 
	private reloadData(target: string): void {
		// console.log('[@owservable] -> OwservableClient reloadData: ${target}`);
		const store: AStore = this._stores.get(target);
		store.restartSubscription();
	}
 
	private updateSubscription(subscriptionConfig: StoreSubscriptionUpdateType): void {
		const {target, scope, observe, config} = subscriptionConfig;
		// console.log('[@owservable] -> OwservableClient updateSubscription: ${target}`);
 
		let store: AStore = this._stores.get(target);
		if (store) {
			store.config = config;
		} else {
			store = storeFactory(scope, observe, target);
 
			this._stores.set(target, store);
			const subscription: Subscription = store.subscribe({
				next: async (m: any): Promise<void> => {
					Iif (!this.isValidTarget(target)) return;
 
					const process: Function = DataMiddlewareMap.getMiddleware(observe);
					Iif (!process) return this.next(m);
 
					const r: any = await process(m, this._connectionManager.user);
					return this.next(r);
				},
				error: (e: any): void => this.error(e),
				complete: (): void => this.complete()
			});
			this._subscriptions.set(target, subscription);
 
			store.config = config;
		}
 
		this.sendDebugTargets('updateSubscription', target);
	}
 
	private isValidTarget(target: string): boolean {
		Iif (!this._stores) return false;
		const targets: string[] = Array.from(this._stores.keys());
		return includes(targets, target);
	}
 
	private sendDebugTargets(event: string, target: string) {
		Iif (!this._stores) return false;
		const targets: string[] = Array.from(this._stores.keys());
		this.next({
			type: 'debug', //
			id: new Date().getTime(),
			payload: {
				event,
				target,
				availableTargets: join(targets, ', ')
			}
		});
	}
 
	private clearSubscriptions(): void {
		Iif (this._subscriptions) {
			const subscriptionsKeys = this._subscriptions.keys();
			for (const subscriptionKey of subscriptionsKeys) {
				this._subscriptions.get(subscriptionKey)?.unsubscribe();
			}
			this._subscriptions.clear();
		}
		this._subscriptions = null;
 
		Iif (this._stores) {
			const storesKeys = this._stores.keys();
			for (const storeKey of storesKeys) {
				this._stores.get(storeKey)?.destroy();
			}
			this._stores.clear();
		}
		this._stores = null;
 
		this.sendDebugTargets('clearSubscriptions', '*');
	}
}