-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.mjs
More file actions
135 lines (115 loc) · 4.61 KB
/
Copy pathserver.mjs
File metadata and controls
135 lines (115 loc) · 4.61 KB
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
import express from 'express';
import cors from 'cors';
import fs from 'fs';
import { createClient } from 'db-vendo-client';
import { profile as dbVendoProfile } from 'db-vendo-client/p/db/index.js';
// Default settings
let settings = {
port: 3000,
locations: { defaultResults: 8 },
journeys: { defaultResults: 5, includeStopovers: true },
departures: { defaultDuration: 60 }
};
const settingsPath = './settings.json';
if (fs.existsSync(settingsPath)) {
try {
const parsed = JSON.parse(fs.readFileSync(settingsPath, 'utf8'));
settings = {
port: parsed.port || settings.port,
locations: { ...settings.locations, ...parsed.locations },
journeys: { ...settings.journeys, ...parsed.journeys },
departures:{ ...settings.departures,...parsed.departures }
};
} catch (e) {
console.error('Fehler beim Lesen von settings.json:', e.message);
}
}
// Maps frontend/query product names to db-vendo-client product IDs
const PRODUCT_MAP = {
'long-distance-train': ['nationalExpress', 'national'],
'regional-train': ['regionalExpress', 'regional', 'suburban'],
'tram': ['tram'],
'bus': ['bus'],
'subway': ['subway'],
'ferry': ['ferry'],
};
const ALL_PRODUCTS = ['nationalExpress', 'national', 'regionalExpress', 'regional', 'suburban', 'bus', 'ferry', 'subway', 'tram', 'taxi'];
function parseProducts(productsParam) {
if (!productsParam) return null;
const requested = productsParam.split(',').flatMap(p => PRODUCT_MAP[p] ?? []);
return Object.fromEntries(ALL_PRODUCTS.map(p => [p, requested.includes(p)]));
}
async function resolveStation(client, value) {
if (/^\d{6,}$/.test(value)) return value;
const hits = await client.locations(value, { results: 1, stops: true, addresses: false });
if (!hits.length) throw new Error(`Haltestelle nicht gefunden: "${value}"`);
return hits[0].id;
}
const app = express();
const port = process.env.PORT || settings.port;
const client = createClient(dbVendoProfile, 'db-api-wrapper');
app.use(cors());
app.use(express.json());
// Health check
app.get('/', (req, res) => {
res.json({ message: 'DB API Wrapper is running!', version: '1.0.0' });
});
// 1. Haltestellen / Orte suchen
app.get('/locations', async (req, res) => {
try {
const { query, results } = req.query;
if (!query) return res.status(400).json({ error: 'Parameter "query" ist erforderlich' });
const locations = await client.locations(query, {
results: results ? parseInt(results) : settings.locations.defaultResults,
stops: true,
addresses: true,
poi: false,
});
res.json(locations);
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// 2. Routen berechnen
app.get('/journeys', async (req, res) => {
try {
const { from, to } = req.query;
if (!from || !to) return res.status(400).json({ error: 'Parameter "from" und "to" sind erforderlich' });
const fromId = await resolveStation(client, from);
const toId = await resolveStation(client, to);
const options = {
results: req.query.results ? parseInt(req.query.results) : settings.journeys.defaultResults,
stopovers: settings.journeys.includeStopovers,
};
if (req.query.departure) options.departure = new Date(req.query.departure);
if (req.query.bike !== undefined) options.bike = req.query.bike === 'true';
if (req.query.accessibility) options.accessibility = req.query.accessibility;
if (req.query.transfers !== undefined && req.query.transfers !== '') options.transfers = parseInt(req.query.transfers);
const products = parseProducts(req.query.products);
if (products) options.products = products;
const data = await client.journeys(fromId, toId, options);
res.json(data);
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// 3. Abfahrtsmonitor
app.get('/departures', async (req, res) => {
try {
const { station, duration } = req.query;
if (!station) return res.status(400).json({ error: 'Parameter "station" ist erforderlich' });
const stationId = await resolveStation(client, station);
const data = await client.departures(stationId, {
duration: duration ? parseInt(duration) : settings.departures.defaultDuration,
});
res.json(data);
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// Serve index.html at /ui — keeps GET / free for the JSON health check
app.use(express.static('.'));
app.listen(port, () => {
console.log(`DB API Wrapper läuft auf http://localhost:${port}`);
console.log(`Beispiel: http://localhost:${port}/journeys?from=Frankfurt(Main)Hbf&to=Berlin+Hbf`);
});