libre-routing
Version:
This library was generated with [Nx](https://nx.dev).
158 lines • 6.83 kB
JavaScript
import { __awaiter } from "tslib";
import { decode } from '@liberty-rider/flexpolyline';
import * as simplify from 'simplify-js';
import bbox from '@turf/bbox';
import { featureCollection, lineString, } from '@turf/helpers';
import { Requester } from '../../utils/requester';
import { UnauthorizedError } from '../errors/unauthorized';
import { selectRouteByStrategy } from './utils/select-route-strategy';
export class HereExecutor {
constructor() {
this.requester = new Requester();
}
request(opts) {
return __awaiter(this, void 0, void 0, function* () {
try {
const data = yield this.requester.request(opts.url, Object.assign({ method: 'POST', headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
}, body: JSON.stringify({}) }, opts.requestParams));
if (!data.routes ||
data.routes.length === 0 ||
violatedResponseNotices(data, opts.routeExcludeNotice)) {
throw new Error('No routes found');
}
const routesSummary = data.routes.map((route, index) => summaryRoutes(route, index, opts.shapePolylinePrecision));
const selectedRouteId = selectRouteByStrategy(routesSummary, opts.selectRouteStrategy);
const features = routesSummary.reduce((acc, c) => {
return [
...acc,
...c.shape.features.map((f) => (Object.assign(Object.assign({}, f), { properties: Object.assign(Object.assign({}, f.properties), { selected: selectedRouteId === f.properties.routeId }) }))),
];
}, []);
const FC = featureCollection(features);
return {
routesShapeBounds: bbox(FC),
rawResponse: data,
routes: routesSummary,
selectedRouteId,
routesShapeGeojson: {
type: 'geojson',
data: FC,
},
};
}
catch (error) {
if (error instanceof Response) {
const response = error;
const body = yield response.json();
if (response.status === 401) {
throw new UnauthorizedError(body);
}
}
throw error;
}
});
}
hasPendingRequests() {
return this.requester.hasPendingRequests;
}
abortAllRequests() {
this.requester.abortAllRequests();
}
}
const summaryRoutes = (route, routeId, precision) => {
const { distance, cost, durationTime, waypoints, path, shape, shapePath, turnByTurnActions, } = route.sections.reduce((acc, section, index) => {
var _a, _b, _c;
const cost = (section.tolls || []).reduce((costAcc, toll) => (toll.fares || []).forEach((fare) => (costAcc += (fare.convertedPrice || fare.price).value)), 0);
const durationTime = ((_a = section.summary) === null || _a === void 0 ? void 0 : _a.duration) || 0;
const waypoints = [];
if (section.departure.place.originalLocation) {
//@ts-ignore
waypoints.push(section.departure.place.location);
}
// Push departure location
if (section.arrival.place.originalLocation &&
((route.sections.length >= 2 && index === route.sections.length - 1) ||
route.sections.length === 1)) {
//@ts-ignore
waypoints.push(section.arrival.place.location);
}
const path = decodePolyline(section.polyline);
const shapePath = simplifyPath(path, precision);
const turnByTurnActions = (section.turnByTurnActions || []).map((action) => {
const [lat, lng] = path[action.offset];
return Object.assign(Object.assign({}, action), { position: { lat, lng } });
});
const shape = lineString(shapePath, {
waypoint: acc.waypointIndex,
routeId,
});
return {
distance: acc.distance + ((_b = section.summary) === null || _b === void 0 ? void 0 : _b.length) || 0,
durationTime: acc.durationTime + durationTime,
cost: acc.cost + cost,
waypoints: [...acc.waypoints, ...waypoints],
path: [...acc.path, ...path],
turnByTurnActions: [...acc.turnByTurnActions, ...turnByTurnActions],
shape: featureCollection([...(((_c = acc.shape) === null || _c === void 0 ? void 0 : _c.features) || []), shape]),
shapePath: [...acc.shapePath, ...shapePath],
waypointIndex: section.type === 'vehicle' &&
route.sections[index + 1] &&
route.sections[index + 1].type === 'vehicle'
? acc.waypointIndex + 1
: acc.waypointIndex,
};
}, {
distance: 0,
cost: 0,
waypoints: [],
path: [],
durationTime: 0,
turnByTurnActions: [],
shape: null,
shapePath: [],
waypointIndex: 0,
});
return {
durationTime,
distance,
cost,
path,
arriveTime: new Date(route.sections[route.sections.length - 1].arrival.time),
departureTime: new Date(route.sections[0].departure.time),
id: routeId,
waypoints,
label: route.routeLabels
? route.routeLabels.map((l) => l.name.value).join(', ')
: undefined,
shape,
turnByTurnActions,
shapePath,
rawRoute: route,
};
};
const violatedResponseNotices = (data, routeExcludeNotice) => {
if (violatedNotices(data.notices || [], routeExcludeNotice)) {
return true;
}
return (data.routes || []).some((route) => (route.sections || []).some((section) => violatedNotices(section.notices || [], routeExcludeNotice)));
};
const violatedNotices = (notices, routeExcludeNotice) => {
return notices.some((notice) => {
const definition = routeExcludeNotice[notice.severity];
return (definition && (definition === 'all' || definition.includes(notice.code)));
});
};
export function posIsDiff(posA, posB) {
const { lat: latA, lng: lngA } = posA;
const { lat: latB, lng: lngB } = posB;
return (latA.toFixed(6) !== latB.toFixed(6) || lngA.toFixed(6) !== lngB.toFixed(6));
}
function decodePolyline(polyline) {
return decode(polyline).polyline;
}
function simplifyPath(path, precision) {
return simplify(path.map(([x, y]) => ({ x, y })), precision, true).map((p) => [+p.y.toFixed(6), +p.x.toFixed(6)]);
}
//# sourceMappingURL=here.executor.js.map