aboutsummaryrefslogtreecommitdiffstats
path: root/src/lib/motis-api.ts
diff options
context:
space:
mode:
Diffstat (limited to 'src/lib/motis-api.ts')
-rw-r--r--src/lib/motis-api.ts57
1 files changed, 57 insertions, 0 deletions
diff --git a/src/lib/motis-api.ts b/src/lib/motis-api.ts
new file mode 100644
index 0000000..1d43eea
--- /dev/null
+++ b/src/lib/motis-api.ts
@@ -0,0 +1,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;