All files / src owservable.client.ts

98.87% Statements 88/89
92.5% Branches 37/40
94.73% Functions 18/19
100% Lines 81/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      2x 2x     2x   2x       2x     32x             32x 32x 32x 32x         1x 1x 1x         3x 2x   2x           7x   1x     1x 1x     1x 1x 1x       1x     1x     1x         1x 1x       1x 1x 1x       48x 48x   48x 48x   48x 48x           2x 2x   2x 2x   2x         1x 1x       7x     7x 7x 1x   6x   6x 6x 3x 3x   2x 2x   1x 1x   1x 1x   6x   6x     7x       5x 4x 4x       9x 8x 8x                       2x 1x 1x 2x   1x   2x   2x 1x 1x 2x   1x   2x   2x      
'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}]`);
		if (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();
		Eif (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> => {
					if (!this.isValidTarget(target)) return;
 
					const process: Function = DataMiddlewareMap.getMiddleware(observe);
					if (!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 {
		if (!this._stores) return false;
		const targets: string[] = Array.from(this._stores.keys());
		return includes(targets, target);
	}
 
	private sendDebugTargets(event: string, target: string) {
		if (!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 {
		if (this._subscriptions) {
			const subscriptionsKeys = this._subscriptions.keys();
			for (const subscriptionKey of subscriptionsKeys) {
				this._subscriptions.get(subscriptionKey)?.unsubscribe();
			}
			this._subscriptions.clear();
		}
		this._subscriptions = null;
 
		if (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', '*');
	}
}