| 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 { ReplaySubject } from '../../ReplaySubject'; |
| 7 |
import { Observer, NextObserver } from '../../types'; |
| 8 |
|
| 9 |
/** |
| 10 |
* WebSocketSubjectConfig is a plain Object that allows us to make our |
| 11 |
* webSocket configurable. |
| 12 |
* |
| 13 |
* <span class="informal">Provides flexibility to {@link webSocket}</span> |
| 14 |
* |
| 15 |
* It defines a set of properties to provide custom behavior in specific |
| 16 |
* moments of the socket's lifecycle. When the connection opens we can |
| 17 |
* use `openObserver`, when the connection is closed `closeObserver`, if we |
| 18 |
* are interested in listening for data coming from server: `deserializer`, |
| 19 |
* which allows us to customize the deserialization strategy of data before passing it |
| 20 |
* to the socket client. By default, `deserializer` is going to apply `JSON.parse` to each message coming |
| 21 |
* from the Server. |
| 22 |
* |
| 23 |
* ## Examples |
| 24 |
* |
| 25 |
* **deserializer**, the default for this property is `JSON.parse` but since there are just two options |
| 26 |
* for incoming data, either be text or binary data. We can apply a custom deserialization strategy |
| 27 |
* or just simply skip the default behaviour. |
| 28 |
* |
| 29 |
* ```ts |
| 30 |
* import { webSocket } from 'rxjs/webSocket'; |
| 31 |
* |
| 32 |
* const wsSubject = webSocket({ |
| 33 |
* url: 'ws://localhost:8081', |
| 34 |
* //Apply any transformation of your choice. |
| 35 |
* deserializer: ({ data }) => data |
| 36 |
* }); |
| 37 |
* |
| 38 |
* wsSubject.subscribe(console.log); |
| 39 |
* |
| 40 |
* // Let's suppose we have this on the Server: ws.send('This is a msg from the server') |
| 41 |
* //output |
| 42 |
* // |
| 43 |
* // This is a msg from the server |
| 44 |
* ``` |
| 45 |
* |
| 46 |
* **serializer** allows us to apply custom serialization strategy but for the outgoing messages. |
| 47 |
* |
| 48 |
* ```ts |
| 49 |
* import { webSocket } from 'rxjs/webSocket'; |
| 50 |
* |
| 51 |
* const wsSubject = webSocket({ |
| 52 |
* url: 'ws://localhost:8081', |
| 53 |
* // Apply any transformation of your choice. |
| 54 |
* serializer: msg => JSON.stringify({ channel: 'webDevelopment', msg: msg }) |
| 55 |
* }); |
| 56 |
* |
| 57 |
* wsSubject.subscribe(() => subject.next('msg to the server')); |
| 58 |
* |
| 59 |
* // Let's suppose we have this on the Server: |
| 60 |
* // ws.on('message', msg => console.log); |
| 61 |
* // ws.send('This is a msg from the server'); |
| 62 |
* // output at server side: |
| 63 |
* // |
| 64 |
* // {"channel":"webDevelopment","msg":"msg to the server"} |
| 65 |
* ``` |
| 66 |
* |
| 67 |
* **closeObserver** allows us to set a custom error when an error raises up. |
| 68 |
* |
| 69 |
* ```ts |
| 70 |
* import { webSocket } from 'rxjs/webSocket'; |
| 71 |
* |
| 72 |
* const wsSubject = webSocket({ |
| 73 |
* url: 'ws://localhost:8081', |
| 74 |
* closeObserver: { |
| 75 |
* next() { |
| 76 |
* const customError = { code: 6666, reason: 'Custom evil reason' } |
| 77 |
* console.log(`code: ${ customError.code }, reason: ${ customError.reason }`); |
| 78 |
* } |
| 79 |
* } |
| 80 |
* }); |
| 81 |
* |
| 82 |
* // output |
| 83 |
* // code: 6666, reason: Custom evil reason |
| 84 |
* ``` |
| 85 |
* |
| 86 |
* **openObserver**, Let's say we need to make some kind of init task before sending/receiving msgs to the |
| 87 |
* webSocket or sending notification that the connection was successful, this is when |
| 88 |
* openObserver is useful for. |
| 89 |
* |
| 90 |
* ```ts |
| 91 |
* import { webSocket } from 'rxjs/webSocket'; |
| 92 |
* |
| 93 |
* const wsSubject = webSocket({ |
| 94 |
* url: 'ws://localhost:8081', |
| 95 |
* openObserver: { |
| 96 |
* next: () => { |
| 97 |
* console.log('Connection ok'); |
| 98 |
* } |
| 99 |
* } |
| 100 |
* }); |
| 101 |
* |
| 102 |
* // output |
| 103 |
* // Connection ok |
| 104 |
* ``` |
| 105 |
*/ |
| 106 |
export interface WebSocketSubjectConfig<T> { |
| 107 |
/** The url of the socket server to connect to */ |
| 108 |
url: string; |
| 109 |
/** The protocol to use to connect */ |
| 110 |
protocol?: string | Array<string>; |
| 111 |
/** @deprecated Will be removed in v8. Use {@link deserializer} instead. */ |
| 112 |
resultSelector?: (e: MessageEvent) => T; |
| 113 |
/** |
| 114 |
* A serializer used to create messages from passed values before the |
| 115 |
* messages are sent to the server. Defaults to JSON.stringify. |
| 116 |
*/ |
| 117 |
serializer?: (value: T) => WebSocketMessage; |
| 118 |
/** |
| 119 |
* A deserializer used for messages arriving on the socket from the |
| 120 |
* server. Defaults to JSON.parse. |
| 121 |
*/ |
| 122 |
deserializer?: (e: MessageEvent) => T; |
| 123 |
/** |
| 124 |
* An Observer that watches when open events occur on the underlying web socket. |
| 125 |
*/ |
| 126 |
openObserver?: NextObserver<Event>; |
| 127 |
/** |
| 128 |
* An Observer that watches when close events occur on the underlying web socket |
| 129 |
*/ |
| 130 |
closeObserver?: NextObserver<CloseEvent>; |
| 131 |
/** |
| 132 |
* An Observer that watches when a close is about to occur due to |
| 133 |
* unsubscription. |
| 134 |
*/ |
| 135 |
closingObserver?: NextObserver<void>; |
| 136 |
/** |
| 137 |
* A WebSocket constructor to use. This is useful for situations like using a |
| 138 |
* WebSocket impl in Node (WebSocket is a DOM API), or for mocking a WebSocket |
| 139 |
* for testing purposes |
| 140 |
*/ |
| 141 |
WebSocketCtor?: { new (url: string, protocols?: string | string[]): WebSocket }; |
| 142 |
/** Sets the `binaryType` property of the underlying WebSocket. */ |
| 143 |
binaryType?: 'blob' | 'arraybuffer'; |
| 144 |
} |
| 145 |
|
| 146 |
const DEFAULT_WEBSOCKET_CONFIG: WebSocketSubjectConfig<any> = { |
| 147 |
url: '', |
| 148 |
deserializer: (e: MessageEvent) => JSON.parse(e.data), |
| 149 |
serializer: (value: any) => JSON.stringify(value), |
| 150 |
}; |
| 151 |
|
| 152 |
const WEBSOCKETSUBJECT_INVALID_ERROR_OBJECT = |
| 153 |
'WebSocketSubject.error must be called with an object with an error code, and an optional reason: { code: number, reason: string }'; |
| 154 |
|
| 155 |
export type WebSocketMessage = string | ArrayBuffer | Blob | ArrayBufferView; |
| 156 |
|
| 157 |
export class WebSocketSubject<T> extends AnonymousSubject<T> { |
| 158 |
// @ts-ignore: Property has no initializer and is not definitely assigned |
| 159 |
private _config: WebSocketSubjectConfig<T>; |
| 160 |
|
| 161 |
/** @internal */ |
| 162 |
// @ts-ignore: Property has no initializer and is not definitely assigned |
| 163 |
_output: Subject<T>; |
| 164 |
|
| 165 |
private _socket: WebSocket | null = null; |
| 166 |
|
| 167 |
constructor(urlConfigOrSource: string | WebSocketSubjectConfig<T> | Observable<T>, destination?: Observer<T>) { |
| 168 |
super(); |
| 169 |
if (urlConfigOrSource instanceof Observable) { |
| 170 |
this.destination = destination; |
| 171 |
this.source = urlConfigOrSource as Observable<T>; |
| 172 |
} else { |
| 173 |
const config = (this._config = { ...DEFAULT_WEBSOCKET_CONFIG }); |
| 174 |
this._output = new Subject<T>(); |
| 175 |
if (typeof urlConfigOrSource === 'string') { |
| 176 |
config.url = urlConfigOrSource; |
| 177 |
} else { |
| 178 |
for (const key in urlConfigOrSource) { |
| 179 |
if (urlConfigOrSource.hasOwnProperty(key)) { |
| 180 |
(config as any)[key] = (urlConfigOrSource as any)[key]; |
| 181 |
} |
| 182 |
} |
| 183 |
} |
| 184 |
|
| 185 |
if (!config.WebSocketCtor && WebSocket) { |
| 186 |
config.WebSocketCtor = WebSocket; |
| 187 |
} else if (!config.WebSocketCtor) { |
| 188 |
throw new Error('no WebSocket constructor can be found'); |
| 189 |
} |
| 190 |
this.destination = new ReplaySubject(); |
| 191 |
} |
| 192 |
} |
| 193 |
|
| 194 |
/** @deprecated Internal implementation detail, do not use directly. Will be made internal in v8. */ |
| 195 |
lift<R>(operator: Operator<T, R>): WebSocketSubject<R> { |
| 196 |
const sock = new WebSocketSubject<R>(this._config as WebSocketSubjectConfig<any>, this.destination as any); |
| 197 |
sock.operator = operator; |
| 198 |
sock.source = this; |
| 199 |
return sock; |
| 200 |
} |
| 201 |
|
| 202 |
private _resetState() { |
| 203 |
this._socket = null; |
| 204 |
if (!this.source) { |
| 205 |
this.destination = new ReplaySubject(); |
| 206 |
} |
| 207 |
this._output = new Subject<T>(); |
| 208 |
} |
| 209 |
|
| 210 |
/** |
| 211 |
* Creates an {@link Observable}, that when subscribed to, sends a message, |
| 212 |
* defined by the `subMsg` function, to the server over the socket to begin a |
| 213 |
* subscription to data over that socket. Once data arrives, the |
| 214 |
* `messageFilter` argument will be used to select the appropriate data for |
| 215 |
* the resulting Observable. When finalization occurs, either due to |
| 216 |
* unsubscription, completion, or error, a message defined by the `unsubMsg` |
| 217 |
* argument will be sent to the server over the WebSocketSubject. |
| 218 |
* |
| 219 |
* @param subMsg A function to generate the subscription message to be sent to |
| 220 |
* the server. This will still be processed by the serializer in the |
| 221 |
* WebSocketSubject's config. (Which defaults to JSON serialization) |
| 222 |
* @param unsubMsg A function to generate the unsubscription message to be |
| 223 |
* sent to the server at finalization. This will still be processed by the |
| 224 |
* serializer in the WebSocketSubject's config. |
| 225 |
* @param messageFilter A predicate for selecting the appropriate messages |
| 226 |
* from the server for the output stream. |
| 227 |
*/ |
| 228 |
multiplex(subMsg: () => any, unsubMsg: () => any, messageFilter: (value: T) => boolean) { |
| 229 |
const self = this; |
| 230 |
return new Observable((observer: Observer<T>) => { |
| 231 |
try { |
| 232 |
self.next(subMsg()); |
| 233 |
} catch (err) { |
| 234 |
observer.error(err); |
| 235 |
} |
| 236 |
|
| 237 |
const subscription = self.subscribe({ |
| 238 |
next: (x) => { |
| 239 |
try { |
| 240 |
if (messageFilter(x)) { |
| 241 |
observer.next(x); |
| 242 |
} |
| 243 |
} catch (err) { |
| 244 |
observer.error(err); |
| 245 |
} |
| 246 |
}, |
| 247 |
error: (err) => observer.error(err), |
| 248 |
complete: () => observer.complete(), |
| 249 |
}); |
| 250 |
|
| 251 |
return () => { |
| 252 |
try { |
| 253 |
self.next(unsubMsg()); |
| 254 |
} catch (err) { |
| 255 |
observer.error(err); |
| 256 |
} |
| 257 |
subscription.unsubscribe(); |
| 258 |
}; |
| 259 |
}); |
| 260 |
} |
| 261 |
|
| 262 |
private _connectSocket() { |
| 263 |
const { WebSocketCtor, protocol, url, binaryType } = this._config; |
| 264 |
const observer = this._output; |
| 265 |
|
| 266 |
let socket: WebSocket | null = null; |
| 267 |
try { |
| 268 |
socket = protocol ? new WebSocketCtor!(url, protocol) : new WebSocketCtor!(url); |
| 269 |
this._socket = socket; |
| 270 |
if (binaryType) { |
| 271 |
this._socket.binaryType = binaryType; |
| 272 |
} |
| 273 |
} catch (e) { |
| 274 |
observer.error(e); |
| 275 |
return; |
| 276 |
} |
| 277 |
|
| 278 |
const subscription = new Subscription(() => { |
| 279 |
this._socket = null; |
| 280 |
if (socket && socket.readyState === 1) { |
| 281 |
socket.close(); |
| 282 |
} |
| 283 |
}); |
| 284 |
|
| 285 |
socket.onopen = (evt: Event) => { |
| 286 |
const { _socket } = this; |
| 287 |
if (!_socket) { |
| 288 |
socket!.close(); |
| 289 |
this._resetState(); |
| 290 |
return; |
| 291 |
} |
| 292 |
const { openObserver } = this._config; |
| 293 |
if (openObserver) { |
| 294 |
openObserver.next(evt); |
| 295 |
} |
| 296 |
|
| 297 |
const queue = this.destination; |
| 298 |
|
| 299 |
this.destination = Subscriber.create<T>( |
| 300 |
(x) => { |
| 301 |
if (socket!.readyState === 1) { |
| 302 |
try { |
| 303 |
const { serializer } = this._config; |
| 304 |
socket!.send(serializer!(x!)); |
| 305 |
} catch (e) { |
| 306 |
this.destination!.error(e); |
| 307 |
} |
| 308 |
} |
| 309 |
}, |
| 310 |
(err) => { |
| 311 |
const { closingObserver } = this._config; |
| 312 |
if (closingObserver) { |
| 313 |
closingObserver.next(undefined); |
| 314 |
} |
| 315 |
if (err && err.code) { |
| 316 |
socket!.close(err.code, err.reason); |
| 317 |
} else { |
| 318 |
observer.error(new TypeError(WEBSOCKETSUBJECT_INVALID_ERROR_OBJECT)); |
| 319 |
} |
| 320 |
this._resetState(); |
| 321 |
}, |
| 322 |
() => { |
| 323 |
const { closingObserver } = this._config; |
| 324 |
if (closingObserver) { |
| 325 |
closingObserver.next(undefined); |
| 326 |
} |
| 327 |
socket!.close(); |
| 328 |
this._resetState(); |
| 329 |
} |
| 330 |
) as Subscriber<any>; |
| 331 |
|
| 332 |
if (queue && queue instanceof ReplaySubject) { |
| 333 |
subscription.add((queue as ReplaySubject<T>).subscribe(this.destination)); |
| 334 |
} |
| 335 |
}; |
| 336 |
|
| 337 |
socket.onerror = (e: Event) => { |
| 338 |
this._resetState(); |
| 339 |
observer.error(e); |
| 340 |
}; |
| 341 |
|
| 342 |
socket.onclose = (e: CloseEvent) => { |
| 343 |
if (socket === this._socket) { |
| 344 |
this._resetState(); |
| 345 |
} |
| 346 |
const { closeObserver } = this._config; |
| 347 |
if (closeObserver) { |
| 348 |
closeObserver.next(e); |
| 349 |
} |
| 350 |
if (e.wasClean) { |
| 351 |
observer.complete(); |
| 352 |
} else { |
| 353 |
observer.error(e); |
| 354 |
} |
| 355 |
}; |
| 356 |
|
| 357 |
socket.onmessage = (e: MessageEvent) => { |
| 358 |
try { |
| 359 |
const { deserializer } = this._config; |
| 360 |
observer.next(deserializer!(e)); |
| 361 |
} catch (err) { |
| 362 |
observer.error(err); |
| 363 |
} |
| 364 |
}; |
| 365 |
} |
| 366 |
|
| 367 |
/** @internal */ |
| 368 |
protected _subscribe(subscriber: Subscriber<T>): Subscription { |
| 369 |
const { source } = this; |
| 370 |
if (source) { |
| 371 |
return source.subscribe(subscriber); |
| 372 |
} |
| 373 |
if (!this._socket) { |
| 374 |
this._connectSocket(); |
| 375 |
} |
| 376 |
this._output.subscribe(subscriber); |
| 377 |
subscriber.add(() => { |
| 378 |
const { _socket } = this; |
| 379 |
if (this._output.observers.length === 0) { |
| 380 |
if (_socket && (_socket.readyState === 1 || _socket.readyState === 0)) { |
| 381 |
_socket.close(); |
| 382 |
} |
| 383 |
this._resetState(); |
| 384 |
} |
| 385 |
}); |
| 386 |
return subscriber; |
| 387 |
} |
| 388 |
|
| 389 |
unsubscribe() { |
| 390 |
const { _socket } = this; |
| 391 |
if (_socket && (_socket.readyState === 1 || _socket.readyState === 0)) { |
| 392 |
_socket.close(); |
| 393 |
} |
| 394 |
this._resetState(); |
| 395 |
super.unsubscribe(); |
| 396 |
} |
| 397 |
} |