From 1e068f9afc9258103269f76f28266b01023c2dd8 Mon Sep 17 00:00:00 2001 From: SimonVanneste <38662306+SimonVanneste@users.noreply.github.com> Date: Thu, 10 Jan 2019 11:30:28 +0100 Subject: [PATCH] Revert "Error classes" --- src/Context.ts | 5 - src/EventType.ts | 9 +- src/Planner.ts | 18 +--- src/demo.ts | 74 ++++++-------- src/errors/InvalidQueryError.ts | 5 - src/errors/LocationResolverError.ts | 3 - .../JourneyExtractorDefault.ts | 20 ++-- .../PublicTransportPlannerCSAProfile.ts | 98 ++++++++----------- src/query-runner/LocationResolverDefault.ts | 9 +- src/query-runner/QueryRunnerDefault.ts | 13 +-- .../exponential/QueryRunnerExponential.ts | 14 +-- 11 files changed, 92 insertions(+), 176 deletions(-) delete mode 100644 src/errors/InvalidQueryError.ts delete mode 100644 src/errors/LocationResolverError.ts diff --git a/src/Context.ts b/src/Context.ts index f57d1e60..00fb1d6e 100644 --- a/src/Context.ts +++ b/src/Context.ts @@ -1,7 +1,6 @@ // @ts-ignore import { EventEmitter, Listener } from "events"; import { Container, injectable } from "inversify"; -import EventType from "./EventType"; /** * The Context serves as event pass through and holder of the inversify container object. @@ -36,10 +35,6 @@ export default class Context implements EventEmitter { return this.emitter.emit(type, ...args); } - public emitWarning(...args: any[]): boolean { - return this.emit(EventType.Warning, ...args); - } - public listenerCount(type: string | symbol): number { return this.emitter.listenerCount(type); } diff --git a/src/EventType.ts b/src/EventType.ts index f80da91f..d7cfe1a7 100644 --- a/src/EventType.ts +++ b/src/EventType.ts @@ -1,16 +1,11 @@ enum EventType { Query = "query", QueryExponential = "query-exponential", - AbortQuery = "abort-query", - InvalidQuery = "invalid-query", - + QueryAbort = "query-abort", LDFetchGet = "ldfetch-get", - - Warning = "warning", - ConnectionScan = "connection-scan", - InitialReachableStops = "initial-reachable-stops", FinalReachableStops = "final-reachable-stops", + InitialReachableStops = "initial-reachable-stops", AddedNewTransferProfile = "added-new-transfer-profile", } diff --git a/src/Planner.ts b/src/Planner.ts index e287ce1e..441fede4 100644 --- a/src/Planner.ts +++ b/src/Planner.ts @@ -43,21 +43,13 @@ export default class Planner implements EventEmitter { public async query(query: IQuery): Promise> { this.emit(EventType.Query, query); - try { - const iterator = await this.queryRunner.run(query); + const iterator = await this.queryRunner.run(query); - this.once(EventType.AbortQuery, () => { - iterator.close(); - }); + this.once(EventType.QueryAbort, () => { + iterator.close(); + }); - return iterator; - } catch (e) { - if (e.eventType) { - this.context.emit(e.eventType, e.message); - } - - return Promise.reject(); - } + return iterator; } public addListener(type: string | symbol, listener: Listener): this { diff --git a/src/demo.ts b/src/demo.ts index 40fc98de..240f8605 100644 --- a/src/demo.ts +++ b/src/demo.ts @@ -12,14 +12,8 @@ export default async (logResults) => { let scannedConnections = 0; planner - .on(EventType.InvalidQuery, (error) => { - console.log("InvalidQuery", error); - }) - .on(EventType.AbortQuery, (reason) => { - console.log("AbortQuery", reason); - }) - .on(EventType.Query, () => { - console.log("Query"); + .on(EventType.Query, (query) => { + console.log("Query", query); }) .on(EventType.QueryExponential, (query) => { const { minimumDepartureTime, maximumArrivalTime } = query; @@ -34,52 +28,42 @@ export default async (logResults) => { }) .on(EventType.ConnectionScan, (connection) => { scannedConnections++; - }) - .on(EventType.Warning, (e) => { - console.warn(e); }); } - return new Promise((resolve, reject) => { - planner.query({ - publicTransportOnly: true, - // from: "https://data.delijn.be/stops/201657", - // to: "https://data.delijn.be/stops/205910", - // from: "https://data.delijn.be/stops/200455", // Deinze weg op Grammene +456 - // to: "https://data.delijn.be/stops/502481", // Tielt Metaalconstructie Goossens - // from: "https://data.delijn.be/stops/509927", // Tield Rameplein perron 1 - // to: "https://data.delijn.be/stops/200455", // Deinze weg op Grammene +456 - from: "http://irail.be/stations/NMBS/008896925", // Ingelmunster - to: "http://irail.be/stations/NMBS/008892007", // Ghent-Sint-Pieters - minimumDepartureTime: new Date("2019-01-10T08:13:20.530Z"), - maximumTransferDuration: Units.fromHours(0.5), - }) - .then((publicTransportResult) => { - - let i = 0; + const publicTransportResult = await planner.query({ + publicTransportOnly: true, + // from: "https://data.delijn.be/stops/201657", + // to: "https://data.delijn.be/stops/205910", + // from: "https://data.delijn.be/stops/200455", // Deinze weg op Grammene +456 + // to: "https://data.delijn.be/stops/502481", // Tielt Metaalconstructie Goossens + // from: "https://data.delijn.be/stops/509927", // Tield Rameplein perron 1 + // to: "https://data.delijn.be/stops/200455", // Deinze weg op Grammene +456 + from: "http://irail.be/stations/NMBS/008896925", // Ingelmunster + to: "http://irail.be/stations/NMBS/008892007", // Ghent-Sint-Pieters + minimumDepartureTime: new Date(), + maximumTransferDuration: Units.fromHours(0.5), + }); - publicTransportResult.take(3) - .on("data", (path: IPath) => { - ++i; + return new Promise((resolve, reject) => { + let i = 0; - if (logResults) { - console.log(i); - console.log(JSON.stringify(path, null, " ")); - console.log("\n"); - } + publicTransportResult.take(3) + .on("data", (path: IPath) => { + ++i; - if (i === 3) { - resolve(true); - } - }) - .on("end", () => { - resolve(false); - }); + if (logResults) { + console.log(i); + console.log(JSON.stringify(path, null, " ")); + console.log("\n"); + } + if (i === 3) { + resolve(true); + } }) - .catch(() => { + .on("end", () => { resolve(false); }); }); - }; diff --git a/src/errors/InvalidQueryError.ts b/src/errors/InvalidQueryError.ts deleted file mode 100644 index e45a0ec2..00000000 --- a/src/errors/InvalidQueryError.ts +++ /dev/null @@ -1,5 +0,0 @@ -import EventType from "../EventType"; - -export default class InvalidQueryError extends Error { - public eventType = EventType.InvalidQuery; -} diff --git a/src/errors/LocationResolverError.ts b/src/errors/LocationResolverError.ts deleted file mode 100644 index 65175f81..00000000 --- a/src/errors/LocationResolverError.ts +++ /dev/null @@ -1,3 +0,0 @@ -export default class LocationResolverError extends Error { - -} diff --git a/src/planner/public-transport/JourneyExtractorDefault.ts b/src/planner/public-transport/JourneyExtractorDefault.ts index e6140c62..e987b17a 100644 --- a/src/planner/public-transport/JourneyExtractorDefault.ts +++ b/src/planner/public-transport/JourneyExtractorDefault.ts @@ -1,6 +1,5 @@ import { ArrayIterator, AsyncIterator } from "asynciterator"; import { inject, injectable } from "inversify"; -import Context from "../../Context"; import IConnection from "../../fetcher/connections/IConnection"; import ILocation from "../../interfaces/ILocation"; import IPath from "../../interfaces/IPath"; @@ -29,14 +28,9 @@ export default class JourneyExtractorDefault implements IJourneyExtractor { private readonly locationResolver: ILocationResolver; private bestArrivalTime: number[][] = []; - private context: Context; - constructor( - @inject(TYPES.LocationResolver) locationResolver: ILocationResolver, - @inject(TYPES.Context)context?: Context, - ) { + constructor(@inject(TYPES.LocationResolver) locationResolver: ILocationResolver) { this.locationResolver = locationResolver; - this.context = context; } public async extractJourneys( @@ -78,7 +72,7 @@ export default class JourneyExtractorDefault implements IJourneyExtractor { transferProfile.arrivalTime, ); } catch (e) { - this.context.emitWarning(e); + console.warn(e); } } } @@ -179,17 +173,17 @@ export default class JourneyExtractorDefault implements IJourneyExtractor { // Get next profile based on the arrival time at the current location. if (remainingTransfers >= 0) { const currentProfiles: IProfile[] = profilesByStop[currentLocation.id]; - let profileIndex: number = currentProfiles.length - 1; + let i: number = currentProfiles.length - 1; - currentTransferProfile = currentProfiles[profileIndex].transferProfiles[remainingTransfers]; + currentTransferProfile = currentProfiles[i].transferProfiles[remainingTransfers]; departureTime = new Date(currentTransferProfile.departureTime); - while (profileIndex >= 0 && departureTime < exitConnection.arrivalTime) { - currentTransferProfile = currentProfiles[--profileIndex].transferProfiles[remainingTransfers]; + while (i >= 0 && departureTime < exitConnection.arrivalTime) { + currentTransferProfile = currentProfiles[--i].transferProfiles[remainingTransfers]; departureTime = new Date(currentTransferProfile.departureTime); } - if (profileIndex === -1) { + if (i === -1) { // This should never happen. return Promise.reject("Can't find next connection"); } diff --git a/src/planner/public-transport/PublicTransportPlannerCSAProfile.ts b/src/planner/public-transport/PublicTransportPlannerCSAProfile.ts index 14db542c..e8c7db71 100644 --- a/src/planner/public-transport/PublicTransportPlannerCSAProfile.ts +++ b/src/planner/public-transport/PublicTransportPlannerCSAProfile.ts @@ -88,6 +88,18 @@ export default class PublicTransportPlannerCSAProfile implements IPublicTranspor public async plan(query: IResolvedQuery): Promise> { this.query = query; + const departureLocation = this.query.from[0]; + if (!departureLocation.id) { + departureLocation.id = "geo:" + departureLocation.latitude + "," + departureLocation.longitude; + departureLocation.name = "Departure location"; + } + + const arrivalLocation = this.query.to[0]; + if (!arrivalLocation.id) { + arrivalLocation.id = "geo:" + arrivalLocation.latitude + "," + arrivalLocation.longitude; + arrivalLocation.name = "Arrival location"; + } + this.setBounds(); return this.calculateJourneys(); @@ -212,7 +224,7 @@ export default class PublicTransportPlannerCSAProfile implements IPublicTranspor private calculateEarliestArrivalTime(connection: IConnection): IArrivalTimeByTransfers { const remainSeatedTime = this.remainSeated(connection); - if (connection["gtfs:dropOffType"] === DropOffType.NotAvailable) { + if (connection["gtfs:dropOffType"] === "gtfs:NotAvailable") { return remainSeatedTime; } @@ -234,7 +246,7 @@ export default class PublicTransportPlannerCSAProfile implements IPublicTranspor ); if (reachableStops.length === 0 && this.context) { - this.context.emit(EventType.AbortQuery, "No reachable stops at arrival location"); + this.context.emit(EventType.QueryAbort); return false; } @@ -244,18 +256,9 @@ export default class PublicTransportPlannerCSAProfile implements IPublicTranspor } for (const reachableStop of reachableStops) { - if (!this.query.to[0].id && reachableStop.duration === 0) { - this.query.to[0] = reachableStop.stop; - } - this.durationToTargetByStop[reachableStop.stop.id] = reachableStop.duration; } - if (!this.query.to[0].id) { - this.query.to[0].id = "geo:" + this.query.to[0].latitude + "," + this.query.to[0].longitude; - this.query.to[0].name = "Arrival location"; - } - return true; } @@ -269,21 +272,8 @@ export default class PublicTransportPlannerCSAProfile implements IPublicTranspor this.query.minimumWalkingSpeed, ); - const stopIndex = 0; - while (stopIndex < this.initialReachableStops.length && !this.query.from[0].id) { - const reachableStop = this.initialReachableStops[stopIndex]; - if (reachableStop.duration === 0) { - this.query.from[0] = reachableStop.stop; - } - } - - if (!this.query.from[0].id) { - this.query.from[0].id = "geo:" + this.query.from[0].latitude + "," + this.query.from[0].longitude; - this.query.from[0].name = "Departure location"; - } - if (this.initialReachableStops.length === 0 && this.context) { - this.context.emit(EventType.AbortQuery, "No reachable stops at departure location"); + this.context.emit(EventType.QueryAbort); return false; } @@ -412,45 +402,35 @@ export default class PublicTransportPlannerCSAProfile implements IPublicTranspor ); } - try { - const departureStop: ILocation = await this.locationResolver.resolve(connection.departureStop); - const reachableStops: IReachableStop[] = await this.transferReachableStopsFinder.findReachableStops( - departureStop as IStop, - ReachableStopsFinderMode.Source, - this.query.maximumWalkingDuration, - this.query.minimumWalkingSpeed, - ); - - reachableStops.forEach((reachableStop: IReachableStop) => { - if (reachableStop.stop.id !== departureLocation.id) { - this.incorporateInProfile( - connection, - reachableStop.duration, - reachableStop.stop, - earliestArrivalTimeByTransfers, - ); - } - }); + const departureStop: ILocation = await this.locationResolver.resolve(connection.departureStop); + const reachableStops: IReachableStop[] = await this.transferReachableStopsFinder.findReachableStops( + departureStop as IStop, + ReachableStopsFinderMode.Source, + this.query.maximumWalkingDuration, + this.query.minimumWalkingSpeed, + ); - } catch (e) { - this.context.emitWarning(e); - } + reachableStops.forEach((reachableStop: IReachableStop) => { + if (reachableStop.stop.id !== departureLocation.id) { + this.incorporateInProfile( + connection, + reachableStop.duration, + reachableStop.stop, + earliestArrivalTimeByTransfers, + ); + } + }); } private async emitTransferProfile(transferProfile: ITransferProfile, amountOfTransfers: number): Promise { - try { - const departureStop = await this.locationResolver.resolve(transferProfile.enterConnection.departureStop); - const arrivalStop = await this.locationResolver.resolve(transferProfile.exitConnection.arrivalStop); + const departureStop = await this.locationResolver.resolve(transferProfile.enterConnection.departureStop); + const arrivalStop = await this.locationResolver.resolve(transferProfile.exitConnection.arrivalStop); - this.context.emit(EventType.AddedNewTransferProfile, { - departureStop, - arrivalStop, - amountOfTransfers, - }); - - } catch (e) { - this.context.emitWarning(e); - } + this.context.emit(EventType.AddedNewTransferProfile, { + departureStop, + arrivalStop, + amountOfTransfers, + }); } private incorporateInProfile( diff --git a/src/query-runner/LocationResolverDefault.ts b/src/query-runner/LocationResolverDefault.ts index e2303f7f..8283d19e 100644 --- a/src/query-runner/LocationResolverDefault.ts +++ b/src/query-runner/LocationResolverDefault.ts @@ -1,5 +1,4 @@ import { inject, injectable } from "inversify"; -import LocationResolverError from "../errors/LocationResolverError"; import IStop from "../fetcher/stops/IStop"; import IStopsProvider from "../fetcher/stops/IStopsProvider"; import ILocation from "../interfaces/ILocation"; @@ -24,7 +23,7 @@ export default class LocationResolverDefault implements ILocationResolver { return this.resolveById(input); } - return Promise.reject(new LocationResolverError(`Location "${input}" is a string, but not an ID`)); + return Promise.reject(`Location "${input}" is a string, but not an ID`); } const location: ILocation = input; @@ -38,9 +37,7 @@ export default class LocationResolverDefault implements ILocationResolver { } if (!hasCoords) { - return Promise.reject( - new LocationResolverError(`Location "${JSON.stringify(input)}" should have latitude and longitude`), - ); + return Promise.reject(`Location "${JSON.stringify(input)}" should have latitude and longitude`); } return location; @@ -58,7 +55,7 @@ export default class LocationResolverDefault implements ILocationResolver { }; } - return Promise.reject(new LocationResolverError(`No fetcher for id ${id}`)); + throw new Error(`No fetcher for id ${id}`); } private isId(testString: string): boolean { diff --git a/src/query-runner/QueryRunnerDefault.ts b/src/query-runner/QueryRunnerDefault.ts index 045bb75f..d78e60cf 100644 --- a/src/query-runner/QueryRunnerDefault.ts +++ b/src/query-runner/QueryRunnerDefault.ts @@ -1,7 +1,6 @@ import { AsyncIterator } from "asynciterator"; import { inject, injectable } from "inversify"; import Defaults from "../Defaults"; -import InvalidQueryError from "../errors/InvalidQueryError"; import ILocation from "../interfaces/ILocation"; import IPath from "../interfaces/IPath"; import IQuery from "../interfaces/IQuery"; @@ -32,7 +31,7 @@ export default class QueryRunnerDefault implements IQueryRunner { return this.publicTransportPlanner.plan(resolvedQuery); } else { - throw new InvalidQueryError("Query should have publicTransportOnly = true"); + return Promise.reject("Query not supported"); } } @@ -77,14 +76,8 @@ export default class QueryRunnerDefault implements IQueryRunner { resolvedQuery.maximumArrivalTime = newMaximumArrivalTime; } - try { - resolvedQuery.from = await this.resolveEndpoint(from); - resolvedQuery.to = await this.resolveEndpoint(to); - - } catch (e) { - return Promise.reject(new InvalidQueryError(e)); - } - + resolvedQuery.from = await this.resolveEndpoint(from); + resolvedQuery.to = await this.resolveEndpoint(to); resolvedQuery.minimumWalkingSpeed = minimumWalkingSpeed || walkingSpeed || Defaults.defaultMinimumWalkingSpeed; resolvedQuery.maximumWalkingSpeed = maximumWalkingSpeed || walkingSpeed || Defaults.defaultMaximumWalkingSpeed; resolvedQuery.maximumWalkingDuration = maximumWalkingDuration || diff --git a/src/query-runner/exponential/QueryRunnerExponential.ts b/src/query-runner/exponential/QueryRunnerExponential.ts index ac25d7de..cde5f40b 100644 --- a/src/query-runner/exponential/QueryRunnerExponential.ts +++ b/src/query-runner/exponential/QueryRunnerExponential.ts @@ -2,7 +2,6 @@ import { AsyncIterator } from "asynciterator"; import { inject, injectable, interfaces } from "inversify"; import Context from "../../Context"; import Defaults from "../../Defaults"; -import InvalidQueryError from "../../errors/InvalidQueryError"; import EventType from "../../EventType"; import ILocation from "../../interfaces/ILocation"; import IPath from "../../interfaces/IPath"; @@ -41,6 +40,7 @@ export default class QueryRunnerExponential implements IQueryRunner { const baseQuery: IResolvedQuery = await this.resolveBaseQuery(query); if (baseQuery.publicTransportOnly) { + const queryIterator = new ExponentialQueryIterator(baseQuery, 15 * 60 * 1000); // const emitQueryIterator = new Emiterator( // queryIterator, @@ -56,7 +56,7 @@ export default class QueryRunnerExponential implements IQueryRunner { return new FilterUniquePathsIterator(subqueryIterator); } else { - throw new InvalidQueryError("Query should have publicTransportOnly = true"); + return Promise.reject("Query not supported"); } } @@ -100,14 +100,8 @@ export default class QueryRunnerExponential implements IQueryRunner { resolvedQuery.minimumDepartureTime = minimumDepartureTime || new Date(); - try { - resolvedQuery.from = await this.resolveEndpoint(from); - resolvedQuery.to = await this.resolveEndpoint(to); - - } catch (e) { - return Promise.reject(new InvalidQueryError(e)); - } - + resolvedQuery.from = await this.resolveEndpoint(from); + resolvedQuery.to = await this.resolveEndpoint(to); resolvedQuery.minimumWalkingSpeed = minimumWalkingSpeed || walkingSpeed || Defaults.defaultMinimumWalkingSpeed; resolvedQuery.maximumWalkingSpeed = maximumWalkingSpeed || walkingSpeed || Defaults.defaultMaximumWalkingSpeed; resolvedQuery.maximumWalkingDuration = maximumWalkingDuration ||