aboutsummaryrefslogtreecommitdiffstats
path: root/src/lib/motis-api.ts
blob: 1d43eeadc60b795224d9d34a47e58e3f341a58cd (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import type { StoptimesResponse } from './motis-types';
export class MotisAPI {
  backend = 'https://api.transitous.org';
  fetch: typeof fetch = (url, init) =>
    fetch(
      `${this.backend}${this.backend.endsWith('/') ? '' : '/'}${
        typeof url === 'string'
          ? url.startsWith('/')
            ? url.substring(1)
            : url
          : url instanceof URL
          ? url.pathname + url.search
          : url
      }`,
      init
    );
  async getStopTimes(
    id: string,
    abortSignal?: AbortSignal,
    arrivals = false,
    limit = 128,
    time: Date | undefined = arrivals
      ? new Date(
          // '2025-07-19T02:03:11Z'
          Date.now() - 1000 * 60
        )
      : undefined
  ) {
    const res = await this.fetch(
      `/api/v1/stoptimes?stopId=${encodeURIComponent(
        id
      )}&n=${encodeURIComponent(limit.toString())}&arriveBy=${
        arrivals ? 'true' : 'false'
      }&withScheduledSkippedStops=${
        localStorage.getItem('with-scheduled-skipped-stops') ?? true
      }&radius=${localStorage.getItem('radius') ?? 350}${
        time ? `&time=${time.toISOString()}` : ''
      }`,
      {
        signal: abortSignal,
      }
    );
    if (res.status !== 200)
      throw new Error(
        `Stop Times: Expected 200 OK, got ${res.status} ${
          res.statusText
        } (${await res
          .text()
          .catch((e) => `Could not get response body: ${e}`)})`
      );
    const json = (await res.json()) as StoptimesResponse;
    // TODO: validate
    return json;
  }
}
export const motis = new MotisAPI();
export default motis;