ctucx.git: trainsearch

web based trip-planner, fork of https://cyberchaos.dev/yuka/trainsearch

commit 3a64b5e7dca03e6110e468eb0f7c88ff822a6b97
parent 1a06dd115c5c2eff1962ba88baec7739c6c2a5fd
Author: Yureka <yuka@yuka.dev>
Date: Sun, 13 Feb 2022 10:36:52 +0100

use hafas-rs wasm module instead of api
7 files changed, 23 insertions(+), 63 deletions(-)
D
src/api.js
|
47
-----------------------------------------------
M
src/app_functions.js
|
12
+++++++-----
A
src/hafas_client.js
|
7
+++++++
M
src/journeyView.js
|
1
-
M
src/journeysView.js
|
1
-
M
src/searchView.js
|
16
++++++++--------
M
webpack.config.js
|
2
+-
diff --git a/src/api.js b/src/api.js
@@ -1,47 +0,0 @@
-import { showDiv, hideDiv } from './helpers.js';
-import { ConsoleLog } from './app_functions.js';
-import { showAlertModal, showLoader, hideOverlay } from './overlays.js';
-
-const api_base = '/api/';
-
-export const request = async (endpoint, params, method, noLoader) => {
-	if (!noLoader) showLoader();
-	let data;
-	const urlparams = [];
-	const addParams = (thing, prefix) => {
-		if (typeof thing === 'object') {
-			for (const [key, val] of Object.entries(thing))
-				addParams(val, prefix.concat([encodeURIComponent(key)]));
-		} else {
-			urlparams.push(`${prefix.join('.')}=${encodeURIComponent(thing)}`);
-		}
-	};
-	addParams(params, []);
-
-	const url = `${api_base}${endpoint}?${urlparams.join('&')}`;
-	try {
-		data = await fetch(url, {method})
-			.then(resp => resp.json());
-	} catch(e) {
-		data = {
-			error: true,
-			msg: 'Failed to fetch. Please check your network connection.',
-		};
-	}
-	if (!noLoader) hideOverlay();
-
-	if (data.error) {
-		showAlertModal(data.msg);
-		throw new Error(data.msg);
-	} else {
-		return data;
-	}
-};
-
-export const get = (endpoint, params, noLoader) => {
-	return request(endpoint, params, 'GET', noLoader);
-};
-
-export const post = async (endpoint, params, noLoader) => {
-	return request(endpoint, params, 'POST', noLoader);
-};
diff --git a/src/app_functions.js b/src/app_functions.js
@@ -1,10 +1,10 @@
 import { db } from './dataStorage.js';
 import { settings, subscribeSettings } from './settings.js';
-import { get, post } from './api.js';
 import { showModal } from './overlays.js';
 import { languages } from './languages.js';
 import { html } from 'lit-html';
 import { formatDateTime, getFrom, getTo } from './helpers.js';
+import { client } from './hafas_client.js';
 
 let ds100 = {};
 

@@ -100,7 +100,7 @@ export const getJourney = async refreshToken => {
 	let data = await db.get('journey', refreshToken);
 	const settings = mkSettings();
 	if (!data || JSON.stringify(data.settings) != JSON.stringify(settings)) {
-		data = await get(`journeys/${encodeURIComponent(refreshToken)}`, settings);
+		data = await client.journeys("${refreshToken}", settings);
 		data.settings = settings;
 		await db.put('journey', data);
 	}

@@ -114,10 +114,10 @@ export const getMoreJourneys = async (slug, mode, hideLoader) => {
 	const saved = await db.get('journeysOverview', slug);
 	const params = { ...saved.params, ...mkSettings() };
 	params[mode+'Than'] = saved[mode+'Ref'];
-	let { departure, arrival, ...moreOpt } = params;
+	let { departure, arrival, from, to, ...moreOpt } = params;
 	console.log(moreOpt);
 	const [newData, ...existingJourneys] = await Promise.all(
-		[ get('journeys', moreOpt) ]
+		[ client.journeys(from, to, moreOpt) ]
 			.concat(saved.journeys.map(getJourney))
 	);
 	console.log(newData);

@@ -157,7 +157,9 @@ const generateSlug = () => {
 
 export const newJourneys = async (params, hideLoader) => {
 	const settings = mkSettings();
-	const data = await get('journeys', { ...settings, ...params }, hideLoader);
+	const { from, to, ...moreOpts } = params;
+	console.log(from, to, { ...settings, ...moreOpts });
+	const data = await client.journeys(from, to, { ...settings, ...moreOpts });
 	data.slug = generateSlug();
 	data.indexOffset = 0;
 	data.params = params;
diff --git a/src/hafas_client.js b/src/hafas_client.js
@@ -0,0 +1,7 @@
+
+export let client;
+
+(async () => {
+	const { JsFetchRequester, DbProfile, HafasClient } = await import('../hafas-rs/pkg/index.js');
+	client = new HafasClient(new DbProfile(), new JsFetchRequester());
+}) ()
diff --git a/src/journeyView.js b/src/journeyView.js
@@ -2,7 +2,6 @@ import { settings } from './settings.js';
 import { showDiv, hideDiv, ElementById, formatDateTime, formatDuration, formatPrice } from './helpers.js';
 import { ConsoleLog, parseName, ds100Names, t, timeTemplate, getJourney, refreshJourneys } from './app_functions.js';
 import { showModal } from './overlays.js';
-import { get } from './api.js';
 import { go } from './router.js';
 import { html, render } from 'lit-html';
 
diff --git a/src/journeysView.js b/src/journeysView.js
@@ -2,7 +2,6 @@ import { showDiv, hideDiv, ElementById, formatDuration, formatFromTo, getFrom, g
 import { parseName, ConsoleLog, t, timeTemplate, getJourneys, getMoreJourneys } from './app_functions.js';
 import { settings, modifySettings } from './settings.js';
 import { setupCanvas } from './canvas.js';
-import { post } from './api.js';
 import { go } from './router.js';
 import { html, render } from 'lit-html';
 import { showAlertModal } from './overlays.js';
diff --git a/src/searchView.js b/src/searchView.js
@@ -1,11 +1,11 @@
 import { showDiv, ElementById, padZeros, isValidDate, formatFromTo } from './helpers.js';
 import { parseName, ConsoleLog, t, loadDS100, getJourneys, getJourneysHistory, newJourneys } from './app_functions.js';
 import { modifySettings, settings } from './settings.js';
-import { get, post } from './api.js';
 import { go } from './router.js';
 import { html, render } from 'lit-html';
 import { showAlertModal, showSelectModal, showLoader, hideOverlay} from './overlays.js';
 import { showSettings } from './settingsView.js';
+import { client } from './hafas_client.js';
 
 const suggestions = {
 	from: {},

@@ -224,7 +224,7 @@ export const search = async (requestId) => {
 	if (Object.entries(suggestions.from).length !== 0) {
 		from = suggestions.from;
 	} else {
-		const data = await get('locations', {'query': fromValue, 'results': 1}, true);
+		const data = await client.locations({'query': fromValue, 'results': 1});
 
 		if (!data[0]) {
 			showAlertModal('Invalid From');

@@ -239,7 +239,7 @@ export const search = async (requestId) => {
 	} else if (Object.entries(suggestions.via).length !== 0) {
 		via = suggestions.via;
 	} else {
-		const data = await get('locations', {'query': viaValue, 'results': 1}, true);
+		const data = await client.locations({'query': viaValue, 'results': 1});
 
 		if (!data[0]) {
 			showAlertModal('Invalid Via');

@@ -252,7 +252,7 @@ export const search = async (requestId) => {
 	if (Object.entries(suggestions.to).length !== 0) {
 		to = suggestions.to;
 	} else {
-		const data = await get('locations', {'query': toValue, 'results': 1}, true);
+		const data = await client.locations({'query': toValue, 'results': 1});
 
 		if (!data[0]) {
 			showAlertModal('Invalid To');

@@ -270,11 +270,11 @@ export const search = async (requestId) => {
 	ConsoleLog(timestamp+'///'+date+' '+time+':00');
 
 	const params = {
-		from: formatFromTo(from),
-		to: formatFromTo(to),
+		from,
+		to,
 		results: 6,
 		accessibility: settings.accessibility,
-		...settings.products,
+		products: settings.products,
 	};
 
 	if (via) params.viaPoint = via;

@@ -300,7 +300,7 @@ const suggestionsTemplate = (data, inputId) => html`
 const loadSuggestions = async (e, input) => {
 	const val = e.target.value;
 	suggestions[e.target.id] = {};
-	const data = val ? await get('locations', {'query': val, 'results': 10}, true) : [];
+	const data = val ? await client.locations({'query': val, 'results': 10}) : [];
 	const suggestionsEl = ElementById(e.target.id+'Suggestions');
 	render(suggestionsTemplate(data, e.target.id), suggestionsEl);
 };
diff --git a/webpack.config.js b/webpack.config.js
@@ -23,7 +23,7 @@ module.exports = {
 
     new WasmPackPlugin({
       crateDirectory: __dirname + "/hafas-rs",
-      extraArgs: "--no-default-features --features all-profiles,js-fetch-requester,wasm-bindings",
+      extraArgs: "--no-default-features --features all-profiles,js-fetch-requester,wasm-bindings,polylines",
     }),
   ]
 };