All files / src/lib/core/message message.service.ts

100% Statements 10/10
100% Branches 0/0
14.29% Functions 1/7
100% Lines 9/9

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 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248                        1x     1x 1x                                                                                                                                                                                                                                                                                                                                                                             1x                 1x                 1x                 1x                 1x                 1x      
import { Injectable } from '@angular/core';
import { Store } from '@ngrx/store';
import { ActivationState, Client, IFrame, IMessage, StompHeaders } from '@stomp/stompjs';
import { combineLatest, from, Observable, of } from 'rxjs';
import { RootState } from '../store';
import { MessageManifest, MessageManifestEntry, MessageManifestEntryMessage, MessageMappingStrategy } from '../message-manifest';
import * as MessageManifestActions from '../message-manifest/message-manifest.actions';
import * as SockJS from 'sockjs-client';
 
@Injectable({
  providedIn: 'root'
})
export class MessageService {
  private readonly clients: Map<string, Client>;
 
  constructor(private readonly store: Store<RootState>) {
    this.clients = new Map();
  }
 
  /* disable test coverage until a strategy for testing can be determined. */
  /* istanbul ignore next */
  /**
   * Connect to the given broker.
   *
   * @param manifest The Message Manifest.
   *
   * @return An empty observable.
   */
  connect(manifest: MessageManifest): Observable<void> {
    const messageConfig = {
      brokerUrl: manifest.brokerUrl,
      // disable reconnectDelay to allow for custom attempts at connecting to avoid infinitely attempting reconnect.
      reconnectDelay: 0
    };
 
    if (!!manifest.options) {
      const keys = [ 'connectHeaders', 'disconnectHeaders', 'heartbeatIncoming', 'heartbeatOutgoing', 'appendMissingNULLonIncoming' ];
      for (const key of keys) {
        if (!!manifest.options[key]) {
          messageConfig[key] = manifest.options[key];
        }
      }
    }
 
    const client = this.createClient(manifest, messageConfig);
 
    client.activate();
 
    return of();
  }
 
  /* disable test coverage until a strategy for testing can be determined. */
  /* istanbul ignore next */
  /**
   * Disconnect from the given broker, completel unsubscribing before disconnecting.
   *
   * @param manifest The Message Manifest.
   */
  disconnect(manifest: MessageManifest): Observable<any> {
    const unsubscriptions = manifest.entries.filter(entry => !!entry.id)
        .map(entry => entry.id)
        .map(id => this.unsubscribe(manifest, id));
 
    return combineLatest(unsubscriptions)
      .pipe(() => from(this.clients
        .get(manifest.name)
        .deactivate()
      ));
  }
 
  /* disable test coverage until a strategy for testing can be determined. */
  /* istanbul ignore next */
  /**
   * Subscribe to the given destination.
   *
   * @param manifest The Message Manifest.
   * @param entry The Message Manifest Entry.
   */
  subscribe(manifest: MessageManifest, entry: MessageManifestEntry): Observable<any> {
    return of(this.clients
      .get(manifest.name)
      .subscribe(entry.destination, (response: IMessage) => {
        let message: any = response.body;
 
        if (entry.mappingStrategy === 'WEAVER') {
          const parsed = JSON.parse(response.body);
 
          message = {
            meta: parsed.meta,
            payload: parsed.payload[Object.keys(parsed.payload)[0]],
            type: Object.keys(parsed.payload)[0]
          };
        } else if (entry.mappingStrategy === 'JSONPARSE') {
          message = JSON.parse(response.body);
        }
 
        this.store.dispatch(MessageManifestActions.receiveMessage({
          manifest,
          entry,
          message
        }));
      })
    );
  }
 
  /* disable test coverage until a strategy for testing can be determined. */
  /* istanbul ignore next */
  /**
   * Unsubscribe a given identifier.
   *
   * @param manifest The message manifest to get the client of.
   * @param id The identifier to unsubscribe from.
   *
   * @return The response from unsubscribe.
   */
  unsubscribe(manifest: MessageManifest, id: string): Observable<any> {
    // tslint:disable:no-void-expression
    return of(this.clients
      .get(manifest.name)
      .unsubscribe(id)
    );
  }
 
  /* disable test coverage until a strategy for testing can be determined. */
  /* istanbul ignore next */
  /**
   * Create a message client using the given manifest and configuration.
   *
   * The onConnect() and onDisconnect will be custom built.
   * All other helpers will bind to the methods on the MessageService.
   *
   * The websocket factory will be assigned to SockJS.
   *
   * @param manifest The message manifest to create a client for.
   * @param config The message configuration.
   *
   * @return The created message client.
   */
  createClient = (manifest: MessageManifest, config: any): Client => {
    const client = new Client();
 
    // tslint:disable:unnecessary-bind
    client.beforeConnect = this.beforeConnect.bind(this);
    client.onChangeState = this.onChangeState.bind(this);
    client.debug = this.debug.bind(this);
    client.onStompError = this.onStompError.bind(this);
    client.onWebSocketClose = this.onWebSocketClose.bind(this);
    client.onWebSocketError = this.onWebSocketError.bind(this);
 
    client.onConnect = (frame: IFrame): void => {
      this.store.dispatch(MessageManifestActions.connectManifestConnected({
        manifest,
        frame: {
          command: frame.command,
          headers: frame.headers
        }
      }));
    };
 
    client.onDisconnect = (frame: IFrame): void => {
      this.store.dispatch(MessageManifestActions.disconnectManifestDisconnected({
        manifest,
        frame: {
          command: frame.command,
          headers: frame.headers
        }
      }));
    };
 
    client.configure(config);
    client.webSocketFactory = () => new SockJS(config.brokerUrl);
 
    this.clients.set(manifest.name, client);
 
    return client;
  };
 
  /* disable test coverage until a strategy for testing can be determined. */
  /* istanbul ignore next */
  /**
   * Delete client from the manifest.
   *
   * @param manifest The Message Manifest.
   *
   * @return An empty observable.
   */
  deleteClient = (manifest: MessageManifest): Observable<void> => {
    this.clients.delete(manifest.name);
 
    return of();
  };
 
  // tslint:disable:no-empty
  // tslint:disable:invalid-void
  /**
   * Callback passed to the Message client to for beforeConnect() calls.
   *
   * @return May return a promise for asynchronous operation.
   */
  beforeConnect = (): void | Promise<void> => {
  };
 
  // tslint:disable:no-empty
  /**
   * Callback passed to the Message client to for onChangeState() calls.
   *
   * @param state The activation state triggering the state change.
   */
  onChangeState = (state: ActivationState): void => {
  };
 
  // tslint:disable:no-empty
  /**
   * Callback passed to the Message client to for debug() calls.
   *
   * @param message The message sent by the Message client debugger.
   */
  debug = (message: string): void => {
  };
 
  // tslint:disable:no-empty
  /**
   * Callback passed to the Message client to for onStompError() calls.
   *
   * @param frame The message frame relating to the error.
   */
  onStompError = (frame: IFrame): void => {
  };
 
  // tslint:disable:no-empty
  /**
   * Callback passed to the Message client to for onWebSocketClose() calls.
   *
   * @param event The event triggering the web socket close.
   */
  onWebSocketClose = (event: any): void => {
  };
 
  // tslint:disable:no-empty
  /**
   * Callback passed to the Message client to for onWebSocketError() calls.
   *
   * @param event The event triggering the web socket error.
   */
  onWebSocketError = (event: any): void => {
  };
}