c53e3b1659fab8bf0738b5c06cb0c1f368e5cfda23c8b7379326c11af8675733534e9ae109de7a5316f98cdb08b88294b267c152f55e54391335661b52f0e4 6.5 KB

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