api/api.ts (view raw)
1import { parse } from "@libs/xml";
2
3const TOKEN = Deno.env.get("API_TOKEN");
4const RequestorRef = "Caroster.io";
5
6const apiFetch = async (
7 query: string
8): Promise<{ response: Response; result: any }> => {
9 const headers = new Headers();
10 headers.append("Authorization", `Bearer ${TOKEN}`);
11 headers.append("Content-Type", "application/xml");
12 const response = await fetch("https://api.opentransportdata.swiss/ojp20", {
13 headers,
14 method: "POST",
15 body: query,
16 });
17 const xml = await response.text();
18 const result = parse(xml);
19 return { response, result };
20};
21
22// Doc: https://opentransportdata.swiss/fr/cookbook/stopeventservice/
23export const getStopEventService = (
24 stopPlaceRef: string,
25 depArrTime: Date = new Date()
26) =>
27 apiFetch(`<?xml version="1.0" encoding="UTF-8"?>
28<OJP xmlns="http://www.vdv.de/ojp" xmlns:siri="http://www.siri.org.uk/siri" version="2.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.vdv.de/ojp ../../../../OJP4/OJP.xsd">
29 <OJPRequest>
30 <siri:ServiceRequest>
31 <siri:RequestTimestamp>${new Date().toISOString()}</siri:RequestTimestamp>
32 <siri:RequestorRef>${RequestorRef}</siri:RequestorRef>
33 <OJPStopEventRequest>
34 <siri:RequestTimestamp>${new Date().toISOString()}</siri:RequestTimestamp>
35 <siri:MessageIdentifier>1220</siri:MessageIdentifier>
36 <Location>
37 <PlaceRef>
38 <siri:StopPointRef>${stopPlaceRef}</siri:StopPointRef>
39 </PlaceRef>
40 <DepArrTime>${depArrTime.toISOString()}</DepArrTime>
41 </Location>
42 <Params>
43 <NumberOfResults>5</NumberOfResults>
44 <StopEventType>departure</StopEventType>
45 <IncludePreviousCalls>false</IncludePreviousCalls>
46 <IncludeOnwardCalls>false</IncludeOnwardCalls>
47 <UseRealtimeData>full</UseRealtimeData>
48 <IncludeStopHierarchy>all</IncludeStopHierarchy>
49 </Params>
50 </OJPStopEventRequest>
51 </siri:ServiceRequest>
52 </OJPRequest>
53</OJP>`);
54
55// Doc: https://opentransportdata.swiss/fr/cookbook/OJPLocationInformationRequest/
56export const getLocationInformationRequest = (textInput: string) =>
57 apiFetch(`<OJP xmlns="http://www.vdv.de/ojp" xmlns:siri="http://www.siri.org.uk/siri" version="2.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.vdv.de/ojp ../../../../Downloads/OJP-changes_for_v1.1%20(1)/OJP-changes_for_v1.1/OJP.xsd">
58 <OJPRequest>
59 <siri:ServiceRequest>
60 <siri:RequestTimestamp>${new Date().toISOString()}</siri:RequestTimestamp>
61 <siri:RequestorRef>${RequestorRef}</siri:RequestorRef>
62 <OJPLocationInformationRequest>
63 <siri:RequestTimestamp>${new Date().toISOString()}</siri:RequestTimestamp>
64 <siri:MessageIdentifier>1220</siri:MessageIdentifier>
65 <InitialInput>
66 <Name>${textInput}</Name>
67 </InitialInput>
68 <Restrictions>
69 <Type>stop</Type>
70 <NumberOfResults>5</NumberOfResults>
71 </Restrictions>
72 </OJPLocationInformationRequest>
73 </siri:ServiceRequest>
74 </OJPRequest>
75</OJP>`);