mobility-toolbox-js 2.0.0-beta.53 → 2.0.0-beta.54

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/api/RealtimeAPI.d.ts +71 -81
  2. package/api/RealtimeAPI.d.ts.map +1 -1
  3. package/api/RealtimeAPI.js +98 -265
  4. package/common/api/WebSocketAPI.d.ts +13 -15
  5. package/common/api/WebSocketAPI.d.ts.map +1 -1
  6. package/common/mixins/RealtimeLayerMixin.d.ts +4 -4
  7. package/common/mixins/RealtimeLayerMixin.d.ts.map +1 -1
  8. package/common/mixins/RealtimeLayerMixin.js +4 -4
  9. package/common/utils/debounceDeparturesMessages.d.ts +12 -0
  10. package/common/utils/debounceDeparturesMessages.d.ts.map +1 -0
  11. package/common/utils/debounceDeparturesMessages.js +24 -0
  12. package/common/utils/debounceWebsocketMessages.d.ts +11 -0
  13. package/common/utils/debounceWebsocketMessages.d.ts.map +1 -0
  14. package/common/utils/debounceWebsocketMessages.js +29 -0
  15. package/common/utils/index.d.ts +3 -0
  16. package/common/utils/index.js +3 -0
  17. package/common/utils/sortAndFilterDepartures.d.ts +16 -0
  18. package/common/utils/sortAndFilterDepartures.d.ts.map +1 -0
  19. package/common/utils/sortAndFilterDepartures.js +58 -0
  20. package/mapbox/layers/RealtimeLayer.d.ts +4 -4
  21. package/mbt.js +183 -244
  22. package/mbt.js.map +3 -3
  23. package/mbt.min.js +11 -11
  24. package/mbt.min.js.map +3 -3
  25. package/ol/layers/RealtimeLayer.d.ts +8 -6
  26. package/ol/layers/RealtimeLayer.d.ts.map +1 -1
  27. package/ol/layers/RealtimeLayer.js +3 -3
  28. package/package.json +1 -1
  29. package/types/common.d.ts +1 -1
  30. package/types/realtime.d.ts +0 -2
  31. package/common/utils/cleanStopTime.d.ts +0 -8
  32. package/common/utils/cleanStopTime.d.ts.map +0 -1
  33. package/common/utils/cleanStopTime.js +0 -25
@@ -1,7 +1,6 @@
1
1
  import WebSocketAPI from '../common/api/WebSocketAPI';
2
- import cleanStopTime from '../common/utils/cleanStopTime';
2
+ import debounceWebsocketMessages from '../common/utils/debounceWebsocketMessages';
3
3
  import getModeSuffix from '../common/utils/getRealtimeModeSuffix';
4
- import compareDepartures from '../common/utils/compareDepartures';
5
4
  /**
6
5
  * Enum for Realtime modes.
7
6
  * @readonly
@@ -46,14 +45,6 @@ class RealtimeAPI {
46
45
  constructor(options = {}) {
47
46
  this.defineProperties(options);
48
47
  /** @ignore */
49
- this.subscribedStationUic = undefined;
50
- /** @ignore */
51
- this.departureUpdateTimeout = undefined;
52
- /** @ignore */
53
- this.maxDepartureAge = 30;
54
- /** @ignore */
55
- this.extraGeoms = {};
56
- /** @ignore */
57
48
  this.prefix = options.prefix || '';
58
49
  /** @ignore */
59
50
  this.onOpen = this.onOpen.bind(this);
@@ -213,7 +204,7 @@ class RealtimeAPI {
213
204
  * @param {boolean} [quiet=false] If true avoid to store the subscription in the subscriptions list.
214
205
  * @private
215
206
  */
216
- subscribe(channel, onSuccess, onError, quiet = false) {
207
+ subscribe(channel, onSuccess, onError = () => { }, quiet = false) {
217
208
  if (!channel || !onSuccess) {
218
209
  return;
219
210
  }
@@ -224,65 +215,14 @@ class RealtimeAPI {
224
215
  *
225
216
  * @param {string} channel Name of the websocket channel to unsubscribe.
226
217
  * @param {string} suffix Suffix to add to the channel name.
227
- * @param {function} cb Callback function to unsubscribe. If null all subscriptions for the channel will be unsubscribed.
218
+ * @param {function} onMessage Callback function to unsubscribe. If null all subscriptions for the channel will be unsubscribed.
228
219
  * @private
229
220
  */
230
- unsubscribe(channel, suffix = '', cb) {
231
- this.wsApi.unsubscribe(`${channel}${getModeSuffix(RealtimeModes.SCHEMATIC, RealtimeModes)}${suffix}`, cb);
232
- this.wsApi.unsubscribe(`${channel}${getModeSuffix(RealtimeModes.TOPOGRAPHIC, RealtimeModes)}${suffix || ''}`, cb);
233
- }
234
- /**
235
- * Filter departures and return an array.
236
- *
237
- * @param {Object} depObject The object containing departures by id.
238
- * @param {boolean} [sortByMinArrivalTime=false] If true sort departures by arrival time.
239
- * @return {Array<Departure>} Return departures array.
240
- * @private
241
- */
242
- filterDepartures(depObject, sortByMinArrivalTime = false) {
243
- const departures = Object.keys(depObject).map((k) => depObject[k]);
244
- departures.sort((a, b) => compareDepartures(a, b, sortByMinArrivalTime));
245
- const futureDate = new Date();
246
- futureDate.setMinutes(futureDate.getMinutes() + this.maxDepartureAge);
247
- const future = futureDate.getTime();
248
- const pastDate = new Date();
249
- pastDate.setMinutes(pastDate.getMinutes() - this.maxDepartureAge);
250
- const past = pastDate.getTime();
251
- const departureArray = [];
252
- const platformsBoarding = [];
253
- let previousDeparture = null;
254
- for (let i = departures.length - 1; i >= 0; i -= 1) {
255
- const departure = Object.assign({}, departures[i]);
256
- const time = new Date(departure.time).getTime();
257
- // Only show departures within the next 30 minutes
258
- if (time > past && time < future) {
259
- // If 2 trains are boarding at the same platform,
260
- // remove the older one.
261
- if (departure.state === 'BOARDING') {
262
- if (platformsBoarding.indexOf(departure.platform) === -1) {
263
- platformsBoarding.push(departure.platform);
264
- }
265
- else {
266
- departure.state = 'HIDDEN';
267
- }
268
- }
269
- // If two trains with the same line number and destinatin
270
- // and a departure difference < 1 minute, hide the second one.
271
- if (previousDeparture &&
272
- departure.to[0] === previousDeparture.to[0] &&
273
- Math.abs(time - previousDeparture.time) < 1000 &&
274
- departure.line.name === previousDeparture.line.name) {
275
- departure.state = 'HIDDEN';
276
- }
277
- if (/(STOP_CANCELLED|JOURNEY_CANCELLED)/.test(departure.state)) {
278
- departure.cancelled = true;
279
- }
280
- previousDeparture = departure;
281
- previousDeparture.time = time;
282
- departureArray.unshift(departure);
283
- }
284
- }
285
- return departureArray;
221
+ unsubscribe(channel, suffix = '', onMessage) {
222
+ const suffixSchenatic = getModeSuffix(RealtimeModes.SCHEMATIC, RealtimeModes);
223
+ const suffixTopographic = getModeSuffix(RealtimeModes.TOPOGRAPHIC, RealtimeModes);
224
+ this.wsApi.unsubscribe(`${channel}${suffixSchenatic}${suffix || ''}`, onMessage);
225
+ this.wsApi.unsubscribe(`${channel}${suffixTopographic}${suffix || ''}`, onMessage);
286
226
  }
287
227
  /**
288
228
  * Subscribe to departures channel of a given station.
@@ -290,67 +230,44 @@ class RealtimeAPI {
290
230
  * @param {number} stationId UIC of the station.
291
231
  * @param {Boolean} sortByMinArrivalTime Sort by minimum arrival time
292
232
  * @param {function(departures:Departure[])} onMessage Function called on each message of the channel.
233
+ * @param {function} onError Callback when the subscription fails.
234
+ * @param {boolean} [quiet=false] If true avoid to store the subscription in the subscriptions list.
293
235
  */
294
- subscribeDepartures(stationId, sortByMinArrivalTime, onMessage) {
295
- window.clearTimeout(this.departureUpdateTimeout);
296
- this.unsubscribeDepartures();
297
- this.subscribedStationUic = stationId;
298
- const channel = stationId ? `timetable_${stationId}` : null;
299
- const departureObject = {};
300
- if (!channel) {
301
- return;
302
- }
303
- const onSuccess = (data) => {
304
- if (data.source === channel) {
305
- const content = data.content || {};
306
- // TODO: These lines seems useless because content.timestamp never exists
307
- // we should check if actually the case
308
- const tDiff = new Date(content.timestamp).getTime() - Date.now();
309
- departureObject[content.call_id] = Object.assign(Object.assign({}, content), { timediff: tDiff });
310
- window.clearTimeout(this.departureUpdateTimeout);
311
- this.departureUpdateTimeout = window.setTimeout(() => {
312
- const departures = this.filterDepartures(departureObject, sortByMinArrivalTime || false);
313
- onMessage(departures);
314
- }, 100);
315
- }
316
- };
317
- this.subscribe(channel, onSuccess, () => {
318
- onMessage([]);
319
- });
236
+ subscribeDepartures(stationId, onMessage, onError = () => { }, quiet = false) {
237
+ this.subscribe(`timetable_${stationId}`, onMessage, onError, quiet);
320
238
  }
321
239
  /**
322
240
  * Unsubscribe from current departures channel.
323
- * @param {function} cb Callback function to unsubscribe. If null all subscriptions for the channel will be unsubscribed.
241
+ * @param {RealtimeStationId} id Station's id
242
+ * @param {function(data: { content: RealtimeDeparture[] })} onMessage Callback function to unsubscribe. If null all subscriptions for the channel will be unsubscribed.
324
243
  */
325
- unsubscribeDepartures(cb) {
326
- if (this.subscribedStationUic) {
327
- this.unsubscribe(`timetable_${this.subscribedStationUic}`, '', cb);
328
- this.subscribedStationUic = undefined;
329
- }
244
+ unsubscribeDepartures(id, onMessage) {
245
+ this.unsubscribe(`timetable_${id}`, '', onMessage);
330
246
  }
331
247
  /**
332
248
  * Subscribe to the disruptions channel for tenant.
333
249
  *
334
- * @param {function(news: RealtimeNews)} onMessage Function called on each message of the channel.
250
+ * @param {function(data: { content: RealtimeNews[] })} onMessage Function called on each message of the channel.
251
+ * @param {function} onError Callback when the subscription fails.
252
+ * @param {boolean} [quiet=false] If true avoid to store the subscription in the subscriptions list.
335
253
  */
336
- subscribeDisruptions(onMessage) {
337
- this.subscribe(`${this.prefix}newsticker`, (data) => {
338
- onMessage(data.content);
339
- });
254
+ subscribeDisruptions(onMessage, onError = () => { }, quiet = false) {
255
+ this.subscribe(`${this.prefix}newsticker`, onMessage, onError, quiet);
340
256
  }
341
257
  /**
342
258
  * Unsubscribe disruptions.
343
- * @param {function} cb Callback function to unsubscribe. If null all subscriptions for the channel will be unsubscribed.
259
+ *
260
+ * @param {function(data: { content: RealtimeNews[] })} onMessage Callback function to unsubscribe. If null all subscriptions for the channel will be unsubscribed.
344
261
  */
345
- unsubscribeDisruptions(cb) {
346
- this.unsubscribe(`${this.prefix}newsticker`, '', cb);
262
+ unsubscribeDisruptions(onMessage) {
263
+ this.unsubscribe(`${this.prefix}newsticker`, '', onMessage);
347
264
  }
348
265
  /**
349
266
  * Return a station with a given uic number and a mode.
350
267
  *
351
268
  * @param {number} uic UIC of the station.
352
269
  * @param {RealtimeMode} mode Realtime mode.
353
- * @return {Promise<Station>} A station.
270
+ * @return {Promise<{data: { content: RealtimeStation }}>} A station.
354
271
  */
355
272
  getStation(uic, mode) {
356
273
  const params = {
@@ -358,42 +275,20 @@ class RealtimeAPI {
358
275
  args: uic,
359
276
  };
360
277
  return new Promise((resolve, reject) => {
361
- this.wsApi.get(params, (data) => {
362
- if (data.content) {
363
- resolve(data.content);
364
- }
365
- else {
366
- reject();
367
- }
368
- });
278
+ this.wsApi.get(params, resolve, reject);
369
279
  });
370
280
  }
371
281
  /**
372
- * Update the model's station list for a given mode and a bbox.
373
- *
282
+ * Get the list of ststions available for a specifc mode. The promise is resolved every 100ms
374
283
  * @param {RealtimeMode} mode Realtime mode.
375
- * @return {Promise<Array<Station>>} An array of stations.
284
+ * @param {number} timeout = 100 Duration in ms between each promise resolve calls.
285
+ * @return {Promise<RealtimeStation[]>} An array of stations.
376
286
  */
377
- getStations(mode) {
378
- const stations = [];
379
- const params = {
380
- channel: `station${getModeSuffix(mode, RealtimeModes)}`,
381
- };
382
- window.clearTimeout(this.stationUpdateTimeout);
383
- return new Promise((resolve, reject) => {
384
- this.wsApi.get(params, (data) => {
385
- if (data.content) {
386
- stations.push(data.content);
387
- window.clearTimeout(this.stationUpdateTimeout);
388
- /** @ignore */
389
- this.stationUpdateTimeout = window.setTimeout(() => {
390
- resolve(stations);
391
- }, 50);
392
- }
393
- else {
394
- reject(data.content);
395
- }
396
- });
287
+ getStations(mode, timeout = 100) {
288
+ return new Promise((resolve) => {
289
+ this.wsApi.get({
290
+ channel: `station${getModeSuffix(mode, RealtimeModes)}`,
291
+ }, debounceWebsocketMessages(resolve, undefined, timeout));
397
292
  });
398
293
  }
399
294
  /**
@@ -401,86 +296,74 @@ class RealtimeAPI {
401
296
  * One message pro station.
402
297
  *
403
298
  * @param {RealtimeMode} mode Realtime mode.
404
- * @param {function(station: Station)} onMessage Function called on each message of the channel.
299
+ * @param {function(data: { content: RealtimeStation })} onMessage Function called on each message of the channel.
300
+ * @param {function} onError Callback when the subscription fails.
301
+ * @param {boolean} [quiet=false] If true avoid to store the subscription in the subscriptions list.
405
302
  */
406
- subscribeStations(mode, onMessage) {
407
- this.unsubscribeStations();
408
- this.subscribe(`station${getModeSuffix(mode, RealtimeModes)}`, (data) => {
409
- if (data.content) {
410
- onMessage(data.content);
411
- }
412
- });
303
+ subscribeStations(mode, onMessage, onError = () => { }, quiet = false) {
304
+ this.subscribe(`station${getModeSuffix(mode, RealtimeModes)}`, onMessage, onError, quiet);
413
305
  }
414
306
  /**
415
307
  * Unsubscribe to stations channel.
416
- * @param {function} cb The listener callback function to unsubscribe. If null all subscriptions for the channel will be unsubscribe.
308
+ * @param {function(data: { content: RealtimeStation })} onMessage The listener callback function to unsubscribe. If null all subscriptions for the channel will be unsubscribe.
417
309
  */
418
- unsubscribeStations(cb) {
419
- window.clearTimeout(this.stationUpdateTimeout);
420
- this.unsubscribe('station', '', cb);
310
+ unsubscribeStations(onMessage) {
311
+ this.unsubscribe('station', '', onMessage);
421
312
  }
422
313
  /**
423
314
  * Subscribe to extra_geoms channel.
424
315
  *
425
- * @param {function(extraGeoms: GeosJSONFeature[])} onMessage Function called on each message of the channel.
316
+ * @param {function(data: { content: RealtimeExtraGeom })} onMessage Function called on each message of the channel.
317
+ * @param {function} onError Callback when the subscription fails.
318
+ * @param {boolean} [quiet=false] If true avoid to store the subscription in the subscriptions list.
426
319
  */
427
- subscribeExtraGeoms(onMessage) {
428
- this.subscribe('extra_geoms', (data) => {
429
- const extraGeom = data.content;
430
- if (extraGeom) {
431
- const { ref } = extraGeom.properties;
432
- if (extraGeom.type === 'Feature') {
433
- this.extraGeoms[ref] = extraGeom;
434
- }
435
- else {
436
- delete this.extraGeoms[ref];
437
- }
438
- onMessage(Object.keys(this.extraGeoms).map((key) => this.extraGeoms[key]));
439
- }
440
- });
320
+ subscribeExtraGeoms(onMessage, onError = () => { }, quiet = false) {
321
+ this.subscribe('extra_geoms', onMessage, onError, quiet);
441
322
  }
442
323
  /**
443
324
  * Unsubscribe to extra_geoms channel.
444
- * @param {function} cb Callback function to unsubscribe. If null all subscriptions for the channel will be unsubscribed.
325
+ * @param {function(data: { content: RealtimeExtraGeom })} onMessage Callback function to unsubscribe. If null all subscriptions for the channel will be unsubscribed.
445
326
  */
446
- unsubscribeExtraGeoms(cb) {
447
- this.unsubscribe('extra_geoms', '', cb);
327
+ unsubscribeExtraGeoms(onMessage) {
328
+ this.unsubscribe('extra_geoms', '', onMessage);
448
329
  }
449
330
  /**
450
331
  * Subscribe to trajectory channel.
451
332
  *
452
333
  * @param {RealtimeMode} mode Realtime mode.
453
- * @param {function(trajectory: RealtimeTrajectory)} onMessage Function called on each message of the channel.
454
- * @param {boolean} quiet If true, the subscription will not send GET and SUB requests to the websocket.
334
+ * @param {function(data: { content: RealtimeTrajectoryResponse[] })} onMessage Function called on each message of the channel.
335
+ * @param {function} onError Callback when the subscription fails.
336
+ * @param {boolean} [quiet=false] If true avoid to store the subscription in the subscriptions list.
455
337
  */
456
- subscribeTrajectory(mode, onMessage, quiet = false) {
338
+ subscribeTrajectory(mode, onMessage, onError = () => { }, quiet = false) {
457
339
  this.unsubscribeTrajectory(onMessage);
458
- this.subscribe(`trajectory${getModeSuffix(mode, RealtimeModes)}`, onMessage, undefined, quiet);
340
+ this.subscribe(`trajectory${getModeSuffix(mode, RealtimeModes)}`, onMessage, onError, quiet);
459
341
  }
460
342
  /**
461
343
  * Unsubscribe to trajectory channels.
462
- * @param {function} cb Callback function to unsubscribe. If null all subscriptions for the channel will be unsubscribed.
344
+ * @param {function(data: { content: RealtimeTrajectoryResponse[] })} onMessage Callback function to unsubscribe. If null all subscriptions for the channel will be unsubscribed.
463
345
  */
464
- unsubscribeTrajectory(cb) {
465
- this.unsubscribe(`trajectory`, '', cb);
346
+ unsubscribeTrajectory(onMessage) {
347
+ this.unsubscribe(`trajectory`, '', onMessage);
466
348
  }
467
349
  /**
468
350
  * Subscribe to deleted_vhicles channel.
469
351
  *
470
352
  * @param {RealtimeMode} mode Realtime mode.
471
- * @param {function(response: { content: Vehicle })} onMessage Function called on each message of the channel.
472
- * @param {boolean} quiet If true, the subscription will not send GET and SUB requests to the websocket.
353
+ * @param {function(data: { content: RealtimeTrainId })} onMessage Callback function to unsubscribe. If null all subscriptions for the channel will be unsubscribed.
354
+ * @param {function} onError Callback when the subscription fails.
355
+ * @param {boolean} [quiet=false] If true avoid to store the subscription in the subscriptions list.
473
356
  */
474
- subscribeDeletedVehicles(mode, onMessage, quiet = false) {
357
+ subscribeDeletedVehicles(mode, onMessage, onError = () => { }, quiet = false) {
475
358
  this.unsubscribeDeletedVehicles(onMessage);
476
- this.subscribe(`deleted_vehicles${getModeSuffix(mode, RealtimeModes)}`, onMessage, undefined, quiet);
359
+ this.subscribe(`deleted_vehicles${getModeSuffix(mode, RealtimeModes)}`, onMessage, onError, quiet);
477
360
  }
478
361
  /**
479
362
  * Unsubscribe to deleted_vhicles channels.
480
- * @param {function} cb Callback function to unsubscribe. If null all subscriptions for the channel will be unsubscribed.
363
+ * @param {function(data: { content: RealtimeTrainId })} onMessage Callback function to unsubscribe. If null all subscriptions for the channel will be unsubscribed.
481
364
  */
482
- unsubscribeDeletedVehicles(cb) {
483
- this.unsubscribe('deleted_vehicles', '', cb);
365
+ unsubscribeDeletedVehicles(onMessage) {
366
+ this.unsubscribe('deleted_vehicles', '', onMessage);
484
367
  }
485
368
  /**
486
369
  * Get a full trajectory of a vehicule .
@@ -488,7 +371,7 @@ class RealtimeAPI {
488
371
  * @param {string} id A vehicle id.
489
372
  * @param {RealtimeMode} mode Realtime mode.
490
373
  * @param {string} generalizationLevel The generalization level to request. Can be one of 5 (more generalized), 10, 30, 100, undefined (less generalized).
491
- * @return {Promise<FullTrajectory>} Return a full trajectory.
374
+ * @return {Promise<{ data: { content: FullTrajectory } }>} Return a full trajectory.
492
375
  */
493
376
  getFullTrajectory(id, mode, generalizationLevel) {
494
377
  const channel = [`full_trajectory${getModeSuffix(mode, RealtimeModes)}`];
@@ -501,129 +384,79 @@ class RealtimeAPI {
501
384
  const params = {
502
385
  channel: channel.join('_'),
503
386
  };
504
- return new Promise((resolve) => {
505
- this.wsApi.get(params, (data) => {
506
- if (data.content) {
507
- resolve(data.content);
508
- }
509
- });
387
+ return new Promise((resolve, reject) => {
388
+ this.wsApi.get(params, resolve, reject);
510
389
  });
511
390
  }
512
- /**
513
- * Get full trajectories of a vehicules .
514
- *
515
- * @param {string[]} ids List of vehicles ids.
516
- * @param {RealtimeMode} mode Realtime mode.
517
- * @param {string} generalizationLevel The generalization level to request. Can be one of '', 'gen5', 'gen10', 'gen30', 'gen100'.
518
- * @return {Promise<Array<FullTrajectory>>} Return an array of full trajectories.
519
- */
520
- getFullTrajectories(ids, mode, generalizationLevel) {
521
- const promises = ids.map((id) => this.getFullTrajectory(id, mode, generalizationLevel));
522
- return Promise.all(promises);
523
- }
524
391
  /**
525
392
  * Subscribe to full_trajectory channel of a given vehicle.
526
393
  *
527
394
  * @param {string} id A vehicle id.
528
395
  * @param {RealtimeMode} mode Realtime mode.
396
+ * @param {function(data: { content: RealtimeFullTrajectory })} onMessage Function called on each message of the channel.
397
+ * @param {function} onError Callback when the subscription fails.
398
+ * @param {boolean} [quiet=false] If true avoid to store the subscription in the subscriptions list.
529
399
  */
530
- subscribeFullTrajectory(id, mode) {
531
- // window.clearTimeout(this.fullTrajectoryUpdateTimeout);
532
- this.unsubscribeFullTrajectory(id);
533
- this.subscribe(`full_trajectory${getModeSuffix(mode, RealtimeModes)}_${id}`, (data) => {
534
- // eslint-disable-next-line no-console
535
- console.log('subscribe full_trajectory', data);
536
- }, (err) => {
537
- // eslint-disable-next-line no-console
538
- console.log('subscribe full_trajectory error', err);
539
- });
400
+ subscribeFullTrajectory(id, mode, onMessage, onError = () => { }, quiet = false) {
401
+ this.subscribe(`full_trajectory${getModeSuffix(mode, RealtimeModes)}_${id}`, onMessage, onError, quiet);
540
402
  }
541
403
  /**
542
404
  * Unsubscribe from full_trajectory channel
543
405
  *
544
406
  * @param {string} id A vehicle id.
545
- * @param {function} cb Callback function to unsubscribe. If null all subscriptions for the channel will be unsubscribed.
407
+ * @param {function(data: { content: RealtimeFullTrajectory })} onMessage Callback function to unsubscribe. If null all subscriptions for the channel will be unsubscribed.
546
408
  */
547
- unsubscribeFullTrajectory(id, cb) {
548
- this.unsubscribe('full_trajectory', `_${id}`, cb);
409
+ unsubscribeFullTrajectory(id, onMessage) {
410
+ this.unsubscribe('full_trajectory', `_${id}`, onMessage);
549
411
  }
550
412
  /**
551
413
  * Get the list of stops for this vehicle.
552
414
  *
553
415
  * @param {string} id A vehicle id.
554
- * @return {Promise<StopSequence>} Returns a stop sequence object.
416
+ * @return {Promise<{ data: { content: StopSequence[] } }>} Returns a stop sequence object.
555
417
  */
556
418
  getStopSequence(id) {
557
- const params = {
558
- channel: `stopsequence_${id}`,
559
- };
560
419
  return new Promise((resolve, reject) => {
561
- this.wsApi.get(params, (data) => {
562
- const content = data.content;
563
- if (content && content.length) {
564
- const stopSequences = content.map((stopSequence) => cleanStopTime(stopSequence));
565
- // Remove the delay from arrivalTime and departureTime
566
- resolve(stopSequences);
567
- }
568
- resolve([]);
569
- }, (err) => {
570
- reject(err);
571
- });
420
+ this.wsApi.get({
421
+ channel: `stopsequence_${id}`,
422
+ }, resolve, reject);
572
423
  });
573
424
  }
574
- /**
575
- * Get a list of stops for a list of vehicles.
576
- *
577
- * @param {string[]} ids List of vehicles ids.
578
- * @return {Promise<Array<StopSequence>>} Return an array of stop sequences.
579
- */
580
- getStopSequences(ids) {
581
- const promises = ids.map((id) => this.getStopSequence(id));
582
- return Promise.all(promises);
583
- }
584
425
  /**
585
426
  * Subscribe to stopsequence channel of a given vehicle.
586
427
  *
587
428
  * @param {string} id A vehicle id.
588
- * @param {function(stopSequence: StopSequence)} onMessage Function called on each message of the channel.
429
+ * @param {function(data: { content: StopSequence[] })} onMessage Function called on each message of the channel.
430
+ * @param {function} onError Callback when the subscription fails.
431
+ * @param {boolean} [quiet=false] If true avoid to store the subscription in the subscriptions list.
589
432
  */
590
- subscribeStopSequence(id, onMessage) {
591
- window.clearTimeout(this.fullTrajectoryUpdateTimeout);
592
- this.unsubscribeStopSequence(id);
593
- this.subscribe(`stopsequence_${id}`, (data) => {
594
- const content = data.content;
595
- if (content && content.length) {
596
- const stopSequences = content.map((stopSequence) => cleanStopTime(stopSequence));
597
- // Remove the delay from arrivalTime and departureTime
598
- onMessage(stopSequences);
599
- }
600
- }, (err) => {
601
- // eslint-disable-next-line no-console
602
- console.log('subscribe stopsequence error', err);
603
- });
433
+ subscribeStopSequence(id, onMessage, onError = () => { }, quiet = false) {
434
+ this.subscribe(`stopsequence_${id}`, onMessage, onError, quiet);
604
435
  }
605
436
  /**
606
437
  * Unsubscribe from stopsequence channel
607
438
  *
608
439
  * @param {string} id A vehicle id.
609
- * @param {function} cb Callback function to unsubscribe. If null all subscriptions for the channel will be unsubscribed.
440
+ * @param {function(data: { content: StopSequence[] })} onMessage Callback function to unsubscribe. If null all subscriptions for the channel will be unsubscribed.
610
441
  */
611
- unsubscribeStopSequence(id, cb) {
612
- this.unsubscribe(`stopsequence`, `_${id}`, cb);
442
+ unsubscribeStopSequence(id, onMessage) {
443
+ this.unsubscribe(`stopsequence`, `_${id}`, onMessage);
613
444
  }
614
445
  /**
615
446
  * Subscribe to healthcheck channel.
616
- * @param {function} onMessage Callback when the subscribe to healthcheck channel succeeds.
447
+ * @param {function(data: { content: string })} onMessage Callback when the subscribe to healthcheck channel succeeds.
448
+ * @param {function} onError Callback when the subscription fails.
449
+ * @param {boolean} [quiet=false] If true avoid to store the subscription in the subscriptions list.
617
450
  */
618
- subscribeHealthCheck(onMessage) {
619
- this.unsubscribeHealthCheck();
620
- this.subscribe('healthcheck', onMessage);
451
+ subscribeHealthCheck(onMessage, onError = () => { }, quiet = false) {
452
+ this.subscribe('healthcheck', onMessage, onError, quiet);
621
453
  }
622
454
  /**
623
455
  * Unsubscribe to healthcheck channel.
456
+ * @param {function(data: { content: string })} onMessage Callback function to unsubscribe. If null all subscriptions for the channel will be unsubscribed.
624
457
  */
625
- unsubscribeHealthCheck() {
626
- this.unsubscribe('healthcheck');
458
+ unsubscribeHealthCheck(onMessage) {
459
+ this.unsubscribe('healthcheck', '', onMessage);
627
460
  }
628
461
  }
629
462
  export default RealtimeAPI;
@@ -1,19 +1,17 @@
1
- import { Feature } from 'geojson';
2
- import { RealtimeDeparture, RealtimeNews, RealtimeStation, RealtimeExtraGeom, RealtimeTrajectory, RealtimeTrajectoryResponse, RealtimeStopSequence, RealtimeFullTrajectory } from '../../types';
1
+ import { RealtimeTrajectoryResponse } from '../../types';
3
2
  export declare type WebSocketAPIParameters = {
4
3
  channel?: string;
5
4
  args?: string | number;
6
5
  id?: string | number;
7
6
  };
8
- export declare type WebSocketAPIMessageEventData = {
7
+ export declare type WebSocketAPIMessageEventData<T> = {
9
8
  timestamp: number;
10
9
  source: string;
11
- content: string | Feature | RealtimeTrajectoryResponse[] | RealtimeDeparture | RealtimeNews[] | RealtimeStation | RealtimeExtraGeom | RealtimeTrajectory | RealtimeStopSequence[] | RealtimeFullTrajectory;
10
+ content: T;
12
11
  client_reference: string | number | null;
13
12
  };
14
- export declare type WebSocketAPIBufferMessageEventData = Omit<WebSocketAPIMessageEventData, 'content'> & {
13
+ export declare type WebSocketAPIBufferMessageEventData = WebSocketAPIMessageEventData<RealtimeTrajectoryResponse[]> & {
15
14
  source: 'buffer';
16
- content: Array<WebSocketAPIMessageEventData>;
17
15
  };
18
16
  export declare type WebSocketAPIMessageEvent = Event & {
19
17
  data: string;
@@ -24,12 +22,12 @@ export interface WebSocketAPIMessageEventListener {
24
22
  /**
25
23
  * This type represents a function that has been call with each feature returned by the websocket.
26
24
  */
27
- export interface WebSocketAPIDataCallback {
28
- (data: WebSocketAPIMessageEventData): void;
25
+ export interface WebSocketAPIMessageCallback<T> {
26
+ (data: WebSocketAPIMessageEventData<T>): void;
29
27
  }
30
28
  export declare type WebSocketAPISubscription = {
31
29
  params: WebSocketAPIParameters;
32
- cb: WebSocketAPIDataCallback;
30
+ cb: WebSocketAPIMessageCallback<any>;
33
31
  errorCb?: EventListener;
34
32
  onMessageCb: WebSocketAPIMessageEventListener;
35
33
  onErrorCb?: EventListener;
@@ -40,7 +38,7 @@ export declare type WebSocketAPISubscribed = {
40
38
  };
41
39
  export declare type WebSocketAPIRequest = {
42
40
  params: WebSocketAPIParameters;
43
- cb: WebSocketAPIDataCallback;
41
+ cb: WebSocketAPIMessageCallback<any>;
44
42
  errorCb?: EventListener;
45
43
  onMessageCb: WebSocketAPIMessageEventListener;
46
44
  onErrorCb?: EventListener;
@@ -107,7 +105,7 @@ declare class WebSocketAPI {
107
105
  * @return {{onMessage: function, errorCb: function}} Object with onMessage and error callbacks
108
106
  * @private
109
107
  */
110
- listen(params: WebSocketAPIParameters, cb: WebSocketAPIDataCallback, errorCb?: EventListener): {
108
+ listen(params: WebSocketAPIParameters, cb: WebSocketAPIMessageCallback<any>, errorCb?: EventListener): {
111
109
  onMessageCb: WebSocketAPIMessageEventListener;
112
110
  onErrorCb?: EventListener;
113
111
  };
@@ -118,7 +116,7 @@ declare class WebSocketAPI {
118
116
  * @param {function} cb Callback used when listen.
119
117
  * @private
120
118
  */
121
- unlisten(params: WebSocketAPIParameters, cb: WebSocketAPIDataCallback): void;
119
+ unlisten(params: WebSocketAPIParameters, cb: WebSocketAPIMessageCallback<any>): void;
122
120
  /**
123
121
  * Sends a get request to the websocket.
124
122
  * The callback is called only once, when the response is received or when the call returns an error.
@@ -128,7 +126,7 @@ declare class WebSocketAPI {
128
126
  * @param {function} onError Callback on error and close event
129
127
  * @private
130
128
  */
131
- get(params: WebSocketAPIParameters, cb: WebSocketAPIDataCallback, errorCb?: EventListener): void;
129
+ get(params: WebSocketAPIParameters, cb: WebSocketAPIMessageCallback<any>, errorCb?: EventListener): void;
132
130
  /**
133
131
  * Subscribe to a given channel.
134
132
  *
@@ -138,14 +136,14 @@ declare class WebSocketAPI {
138
136
  * @param {boolean} quiet if false, no GET or SUB requests are send, only the callback is registered.
139
137
  * @private
140
138
  */
141
- subscribe(params: WebSocketAPIParameters, cb: WebSocketAPIDataCallback, errorCb?: EventListener, quiet?: boolean): void;
139
+ subscribe(params: WebSocketAPIParameters, cb: WebSocketAPIMessageCallback<any>, errorCb?: EventListener, quiet?: boolean): void;
142
140
  /**
143
141
  * Unsubscribe from a channel.
144
142
  * @param {string} source source to unsubscribe from
145
143
  * @param {function} cb Callback function to unsubscribe. If null all subscriptions for the channel will be unsubscribed.
146
144
  * @private
147
145
  */
148
- unsubscribe(source: string, cb?: WebSocketAPIDataCallback): void;
146
+ unsubscribe(source: string, cb?: WebSocketAPIMessageCallback<any>): void;
149
147
  /**
150
148
  * After an auto reconnection we need to re-subscribe to the channels.
151
149
  */
@@ -1 +1 @@
1
- {"version":3,"file":"WebSocketAPI.d.ts","sourceRoot":"","sources":["../../../src/common/api/WebSocketAPI.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AAClC,OAAO,EACL,iBAAiB,EACjB,YAAY,EACZ,eAAe,EACf,iBAAiB,EACjB,kBAAkB,EAClB,0BAA0B,EAC1B,oBAAoB,EACpB,sBAAsB,EACvB,MAAM,aAAa,CAAC;AAErB,MAAM,CAAC,OAAO,MAAM,sBAAsB,GAAG;IAC3C,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,IAAI,CAAC,EAAE,MAAM,GAAG,MAAM,CAAC;IACvB,EAAE,CAAC,EAAE,MAAM,GAAG,MAAM,CAAC;CACtB,CAAC;AAEF,MAAM,CAAC,OAAO,MAAM,4BAA4B,GAAG;IACjD,SAAS,EAAE,MAAM,CAAC;IAClB,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EACH,MAAM,GACN,OAAO,GACP,0BAA0B,EAAE,GAC5B,iBAAiB,GACjB,YAAY,EAAE,GACd,eAAe,GACf,iBAAiB,GACjB,kBAAkB,GAClB,oBAAoB,EAAE,GACtB,sBAAsB,CAAC;IAC3B,gBAAgB,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAAC;CAC1C,CAAC;AAEF,oBAAY,kCAAkC,GAAG,IAAI,CACnD,4BAA4B,EAC5B,SAAS,CACV,GAAG;IACF,MAAM,EAAE,QAAQ,CAAC;IACjB,OAAO,EAAE,KAAK,CA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