1
+ // @ts -types="npm:@types/express"
2
+ import express from "npm:express" ;
3
+ import { RequestType } from "./vendoHandler.ts" ;
4
+ import { DateTime } from "npm:luxon" ;
5
+
6
+ type Query = {
7
+ evaNumber : string ;
8
+ type : RequestType ;
9
+ when ?: string ;
10
+ duration ?: number ;
11
+ results ?: number ;
12
+ }
13
+
14
+ export class CombinedHandler {
15
+ async handleRequest (
16
+ req : express . Request ,
17
+ res : express . Response ,
18
+ ) : Promise < void > {
19
+ let query : Query = req . query as unknown as Query ;
20
+ query = {
21
+ ...req . query as unknown as Query ,
22
+ when : query . when ?? DateTime . now ( ) . toISO ( ) ,
23
+ duration : query . duration ?? 60 ,
24
+ results : query . results ?? 1000 ,
25
+ }
26
+
27
+ if ( ! query . evaNumber ) {
28
+ res . status ( 400 ) . send ( "Station's evaNumber is required" ) ;
29
+ return ;
30
+ }
31
+
32
+ if ( ! query . type ) {
33
+ res . status ( 400 ) . send (
34
+ "Type is required. Expected 'departures' or 'arrivals'" ,
35
+ ) ;
36
+ return ;
37
+ }
38
+
39
+ if ( ! DateTime . fromISO ( query . when ) . isValid ) {
40
+ res . status ( 400 ) . send ( "Invalid date" ) ;
41
+ return ;
42
+ }
43
+
44
+ const now = DateTime . now ( ) . set ( { second : 0 , millisecond : 0 } ) ;
45
+ const diffToStart = Math . round ( DateTime . fromISO ( query . when ) . diff ( now , "hours" ) . hours ) ;
46
+ const diffToEnd = Math . round ( ( DateTime . fromISO ( query . when ) . diff ( now , "hours" ) . minutes + query . duration ) / 60 ) ;
47
+
48
+ // Bahnhof API only allows requests for the next 6 hours
49
+ if ( diffToStart < - 1 || diffToEnd > 6 ) {
50
+ // TODO: somehow url is not correct
51
+ const request = await fetch ( `http://localhost:8000/api/v1/timetable/vendo?evaNumber=${ query . evaNumber } &type=${ query . type } &when=${ encodeURIComponent ( query . when as string ) } &duration=${ query . duration } &results=${ query . results } ` , { method : "GET" } ) ;
52
+ if ( ! request . ok ) {
53
+ res . status ( 200 ) . send ( request . body ) ;
54
+ return ;
55
+ }
56
+
57
+ const data = await request . json ( ) ;
58
+ if ( ! data [ query . type ] || ! Array . isArray ( data [ query . type ] ) ) {
59
+ res . status ( 200 ) . send ( [ ] ) ;
60
+ return ;
61
+ }
62
+
63
+ res . status ( 200 ) . send ( data ) ;
64
+ return ;
65
+ }
66
+
67
+ res . status ( 200 ) . send ( "OK" ) ;
68
+ return ;
69
+ }
70
+ }
0 commit comments