WebSocketSubject.d.ts 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  1. import { Subject, AnonymousSubject } from '../../Subject';
  2. import { Subscriber } from '../../Subscriber';
  3. import { Observable } from '../../Observable';
  4. import { Subscription } from '../../Subscription';
  5. import { Operator } from '../../Operator';
  6. import { Observer, NextObserver } from '../../types';
  7. /**
  8. * WebSocketSubjectConfig is a plain Object that allows us to make our
  9. * webSocket configurable.
  10. *
  11. * <span class="informal">Provides flexibility to {@link webSocket}</span>
  12. *
  13. * It defines a set of properties to provide custom behavior in specific
  14. * moments of the socket's lifecycle. When the connection opens we can
  15. * use `openObserver`, when the connection is closed `closeObserver`, if we
  16. * are interested in listening for data comming from server: `deserializer`,
  17. * which allows us to customize the deserialization strategy of data before passing it
  18. * to the socket client. By default `deserializer` is going to apply `JSON.parse` to each message comming
  19. * from the Server.
  20. *
  21. * ## Example
  22. * **deserializer**, the default for this property is `JSON.parse` but since there are just two options
  23. * for incomming data, either be text or binarydata. We can apply a custom deserialization strategy
  24. * or just simply skip the default behaviour.
  25. * ```ts
  26. * import { webSocket } from 'rxjs/webSocket';
  27. *
  28. * const wsSubject = webSocket({
  29. * url: 'ws://localhost:8081',
  30. * //Apply any transformation of your choice.
  31. * deserializer: ({data}) => data
  32. * });
  33. *
  34. * wsSubject.subscribe(console.log);
  35. *
  36. * // Let's suppose we have this on the Server: ws.send("This is a msg from the server")
  37. * //output
  38. * //
  39. * // This is a msg from the server
  40. * ```
  41. *
  42. * **serializer** allows us tom apply custom serialization strategy but for the outgoing messages
  43. * ```ts
  44. * import { webSocket } from 'rxjs/webSocket';
  45. *
  46. * const wsSubject = webSocket({
  47. * url: 'ws://localhost:8081',
  48. * //Apply any transformation of your choice.
  49. * serializer: msg => JSON.stringify({channel: "webDevelopment", msg: msg})
  50. * });
  51. *
  52. * wsSubject.subscribe(() => subject.next("msg to the server"));
  53. *
  54. * // Let's suppose we have this on the Server: ws.send("This is a msg from the server")
  55. * //output
  56. * //
  57. * // {"channel":"webDevelopment","msg":"msg to the server"}
  58. * ```
  59. *
  60. * **closeObserver** allows us to set a custom error when an error raise up.
  61. * ```ts
  62. * import { webSocket } from 'rxjs/webSocket';
  63. *
  64. * const wsSubject = webSocket({
  65. * url: 'ws://localhost:8081',
  66. * closeObserver: {
  67. next(closeEvent) {
  68. const customError = { code: 6666, reason: "Custom evil reason" }
  69. console.log(`code: ${customError.code}, reason: ${customError.reason}`);
  70. }
  71. }
  72. * });
  73. *
  74. * //output
  75. * // code: 6666, reason: Custom evil reason
  76. * ```
  77. *
  78. * **openObserver**, Let's say we need to make some kind of init task before sending/receiving msgs to the
  79. * webSocket or sending notification that the connection was successful, this is when
  80. * openObserver is usefull for.
  81. * ```ts
  82. * import { webSocket } from 'rxjs/webSocket';
  83. *
  84. * const wsSubject = webSocket({
  85. * url: 'ws://localhost:8081',
  86. * openObserver: {
  87. * next: () => {
  88. * console.log('connetion ok');
  89. * }
  90. * },
  91. * });
  92. *
  93. * //output
  94. * // connetion ok`
  95. * ```
  96. * */
  97. export interface WebSocketSubjectConfig<T> {
  98. /** The url of the socket server to connect to */
  99. url: string;
  100. /** The protocol to use to connect */
  101. protocol?: string | Array<string>;
  102. /** @deprecated use {@link deserializer} */
  103. resultSelector?: (e: MessageEvent) => T;
  104. /**
  105. * A serializer used to create messages from passed values before the
  106. * messages are sent to the server. Defaults to JSON.stringify.
  107. */
  108. serializer?: (value: T) => WebSocketMessage;
  109. /**
  110. * A deserializer used for messages arriving on the socket from the
  111. * server. Defaults to JSON.parse.
  112. */
  113. deserializer?: (e: MessageEvent) => T;
  114. /**
  115. * An Observer that watches when open events occur on the underlying web socket.
  116. */
  117. openObserver?: NextObserver<Event>;
  118. /**
  119. * An Observer than watches when close events occur on the underlying webSocket
  120. */
  121. closeObserver?: NextObserver<CloseEvent>;
  122. /**
  123. * An Observer that watches when a close is about to occur due to
  124. * unsubscription.
  125. */
  126. closingObserver?: NextObserver<void>;
  127. /**
  128. * A WebSocket constructor to use. This is useful for situations like using a
  129. * WebSocket impl in Node (WebSocket is a DOM API), or for mocking a WebSocket
  130. * for testing purposes
  131. */
  132. WebSocketCtor?: {
  133. new (url: string, protocols?: string | string[]): WebSocket;
  134. };
  135. /** Sets the `binaryType` property of the underlying WebSocket. */
  136. binaryType?: 'blob' | 'arraybuffer';
  137. }
  138. export declare type WebSocketMessage = string | ArrayBuffer | Blob | ArrayBufferView;
  139. export declare class WebSocketSubject<T> extends AnonymousSubject<T> {
  140. private _config;
  141. /** @deprecated This is an internal implementation detail, do not use. */
  142. _output: Subject<T>;
  143. private _socket;
  144. constructor(urlConfigOrSource: string | WebSocketSubjectConfig<T> | Observable<T>, destination?: Observer<T>);
  145. lift<R>(operator: Operator<T, R>): WebSocketSubject<R>;
  146. private _resetState;
  147. /**
  148. * Creates an {@link Observable}, that when subscribed to, sends a message,
  149. * defined by the `subMsg` function, to the server over the socket to begin a
  150. * subscription to data over that socket. Once data arrives, the
  151. * `messageFilter` argument will be used to select the appropriate data for
  152. * the resulting Observable. When teardown occurs, either due to
  153. * unsubscription, completion or error, a message defined by the `unsubMsg`
  154. * argument will be send to the server over the WebSocketSubject.
  155. *
  156. * @param subMsg A function to generate the subscription message to be sent to
  157. * the server. This will still be processed by the serializer in the
  158. * WebSocketSubject's config. (Which defaults to JSON serialization)
  159. * @param unsubMsg A function to generate the unsubscription message to be
  160. * sent to the server at teardown. This will still be processed by the
  161. * serializer in the WebSocketSubject's config.
  162. * @param messageFilter A predicate for selecting the appropriate messages
  163. * from the server for the output stream.
  164. */
  165. multiplex(subMsg: () => any, unsubMsg: () => any, messageFilter: (value: T) => boolean): Observable<any>;
  166. private _connectSocket;
  167. /** @deprecated This is an internal implementation detail, do not use. */
  168. _subscribe(subscriber: Subscriber<T>): Subscription;
  169. unsubscribe(): void;
  170. }