api/stopEvent.ts (view raw)
1import { difference } from "@std/datetime/difference";
2import { format } from "@std/datetime/format";
3import { getStopEventService } from "./api.ts";
4import { get } from "../lib/func.ts";
5
6export const getNextDepartures = async (
7 stopRef: string,
8 depArrTime: Date = new Date()
9): Promise<StopEvent[]> => {
10 const { result } = await getStopEventService(stopRef, depArrTime);
11 const stopEventResult =
12 result.OJP.OJPResponse["siri:ServiceDelivery"]["OJPStopEventDelivery"][
13 "StopEventResult"
14 ];
15
16 if (!stopEventResult) return [];
17
18 return stopEventResult
19 .map((stopEvent: any) => {
20 const rawDatetime =
21 get(
22 stopEvent,
23 "StopEvent.ThisCall.CallAtStop.ServiceDeparture.EstimatedTime"
24 ) ||
25 get(
26 stopEvent,
27 "StopEvent.ThisCall.CallAtStop.ServiceDeparture.TimetabledTime"
28 );
29 let datetime = null;
30 let departureIn = null;
31 if (rawDatetime) {
32 datetime = new Date(rawDatetime);
33 departureIn = difference(datetime, new Date(), { units: ["minutes"] });
34 }
35 const serviceType = get(
36 stopEvent,
37 "StopEvent.Service.ProductCategory.Name.Text.#text"
38 );
39 return {
40 from: get(stopEvent, "StopEvent.Service.OriginText.Text.#text"),
41 to: get(stopEvent, "StopEvent.Service.DestinationText.Text.#text"),
42 departure: datetime && format(datetime, "HH:mm"),
43 departureIn: departureIn?.minutes,
44 serviceName: get(
45 stopEvent,
46 "StopEvent.Service.PublishedServiceName.Text.#text"
47 ),
48 serviceType,
49 serviceTypeIcon: getServiceTypeIcon(serviceType),
50 stopName: get(
51 stopEvent,
52 "StopEvent.ThisCall.CallAtStop.StopPointName.Text.#text"
53 ),
54 quay: get(
55 stopEvent,
56 "StopEvent.ThisCall.CallAtStop.PlannedQuay.Text.#text"
57 ),
58 } as StopEvent;
59 })
60 .sort(
61 (eventA: StopEvent, eventB: StopEvent) =>
62 eventA.departureIn - eventB.departureIn
63 );
64};
65
66const getServiceTypeIcon = (serviceType: string) => {
67 const icon = {
68 Bus: "🚍",
69 Tram: "🚊",
70 Zug: "🚆",
71 Schiff: "🛥️",
72 }[serviceType];
73 return icon || serviceType;
74};