-
Notifications
You must be signed in to change notification settings - Fork 36
/
Copy pathquery-gen.ts
270 lines (245 loc) · 7.23 KB
/
query-gen.ts
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
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
import { LonLatOutput } from "@conveyal/lonlat";
import { print } from "graphql";
import {
ModeSetting,
ModeSettingValues,
TransportMode
} from "@opentripplanner/types";
import DefaultPlanQuery from "./planQuery.graphql";
type InputBanned = {
routes?: string;
agencies?: string;
trips?: string;
stops?: string;
stopsHard?: string;
};
type InputPreferred = {
routes?: string;
agencies?: string;
unpreferredCost?: string;
};
type OTPQueryParams = {
arriveBy: boolean;
date?: string;
from: LonLatOutput & { name?: string };
modes: TransportMode[];
modeSettings: ModeSetting[];
time?: string;
numItineraries?: number;
to: LonLatOutput & { name?: string };
banned?: InputBanned;
preferred?: InputPreferred;
};
type GraphQLQuery = {
query: string;
variables: Record<string, unknown>;
};
/**
* Mode Settings can contain additional modes to add to the query,
* this function extracts those additional modes from the settings
* and returns them in an array.
* @param modeSettings List of mode settings with values populated
* @returns Additional transport modes to add to query
*/
export function extractAdditionalModes(
modeSettings: ModeSetting[],
enabledModes: TransportMode[]
): TransportMode[] {
return modeSettings.reduce<TransportMode[]>((prev, cur) => {
// First, ensure that the mode associated with this setting is even enabled
if (!enabledModes.map(m => m.mode).includes(cur.applicableMode)) {
return prev;
}
// In checkboxes, mode must be enabled and have a transport mode in it
if (
(cur.type === "CHECKBOX" || cur.type === "SUBMODE") &&
cur.addTransportMode &&
cur.value
) {
const { addTransportMode } = cur;
return Array.isArray(addTransportMode)
? [...prev, ...addTransportMode]
: [...prev, addTransportMode];
}
if (cur.type === "DROPDOWN") {
const transportMode = cur.options.find(o => o.value === cur.value)
?.addTransportMode;
if (transportMode) {
return [...prev, transportMode];
}
}
return prev;
}, []);
}
/**
* Generates every possible mathematical subset of the input TransportModes.
* Uses code from:
* https://stackoverflow.com/questions/5752002/find-all-possible-subset-combos-in-an-array
* @param array Array of input transport modes
* @returns 2D array representing every possible subset of transport modes from input
*/
function combinations(array: TransportMode[]): TransportMode[][] {
if (!array) return [];
return (
// eslint-disable-next-line no-bitwise
new Array(1 << array.length)
.fill(null)
// eslint-disable-next-line no-bitwise
.map((e1, i) => array.filter((e2, j) => i & (1 << j)))
);
}
/**
* This constant maps all the transport mode to a broader mode type,
* which is used to determine the valid combinations of modes used in query generation.
*/
export const SIMPLIFICATIONS = {
AIRPLANE: "TRANSIT",
BICYCLE: "PERSONAL",
BUS: "TRANSIT",
CABLE_CAR: "TRANSIT",
CAR: "CAR",
FERRY: "TRANSIT",
FLEX: "SHARED", // TODO: this allows FLEX+WALK. Is this reasonable?
FUNICULAR: "TRANSIT",
GONDOLA: "TRANSIT",
RAIL: "TRANSIT",
SCOOTER: "PERSONAL",
SUBWAY: "TRANSIT",
TRAM: "TRANSIT",
TRANSIT: "TRANSIT",
WALK: "WALK"
};
// Inclusion of "TRANSIT" alone automatically implies "WALK" in OTP
const VALID_COMBOS = [
["WALK"],
["PERSONAL"],
["TRANSIT", "SHARED"],
["WALK", "SHARED"],
["TRANSIT"],
["TRANSIT", "PERSONAL"],
["TRANSIT", "CAR"]
];
const BANNED_TOGETHER = ["SCOOTER", "BICYCLE", "CAR"];
export const TRANSIT_SUBMODES = Object.keys(SIMPLIFICATIONS).filter(
mode => SIMPLIFICATIONS[mode] === "TRANSIT" && mode !== "TRANSIT"
);
export const TRANSIT_SUBMODES_AND_TRANSIT = Object.keys(SIMPLIFICATIONS).filter(
mode => SIMPLIFICATIONS[mode] === "TRANSIT"
);
function isCombinationValid(
combo: TransportMode[],
queryTransitSubmodes: string[]
): boolean {
if (combo.length === 0) return false;
// All current qualifiers currently simplify to "SHARED"
const simplifiedModes = Array.from(
new Set(combo.map(c => (c.qualifier ? "SHARED" : SIMPLIFICATIONS[c.mode])))
);
// Ensure that if we have one transit mode, then we include ALL transit modes
if (simplifiedModes.includes("TRANSIT")) {
// Don't allow TRANSIT along with any other submodes
if (queryTransitSubmodes.length && combo.find(c => c.mode === "TRANSIT")) {
return false;
}
if (
combo.reduce((prev, cur) => {
if (queryTransitSubmodes.includes(cur.mode)) {
return prev - 1;
}
return prev;
}, queryTransitSubmodes.length) !== 0
) {
return false;
}
// Continue to the other checks
}
// OTP doesn't support multiple non-walk modes
if (BANNED_TOGETHER.filter(m => combo.find(c => c.mode === m)).length > 1) {
return false;
}
return !!VALID_COMBOS.find(
vc =>
simplifiedModes.every(m => vc.includes(m)) &&
vc.every(m => simplifiedModes.includes(m))
);
}
/**
* Generates a list of queries for OTP to get a comprehensive
* set of results based on the modes input.
* @param params OTP Query Params
* @returns Set of parameters to generate queries
*/
export function generateCombinations(params: OTPQueryParams): OTPQueryParams[] {
const completeModeList = [
...extractAdditionalModes(params.modeSettings, params.modes),
...params.modes
];
// List of the transit *submodes* that are included in the input params
const queryTransitSubmodes = completeModeList
.filter(mode => TRANSIT_SUBMODES.includes(mode.mode))
.map(mode => mode.mode);
return combinations(completeModeList)
.filter(combo => isCombinationValid(combo, queryTransitSubmodes))
.map(combo => ({ ...params, modes: combo }));
}
/**
* Generates a query for OTP GraphQL API based on parameters.
* @param param0 OTP2 Parameters for the query
* @param planQuery Override the default query for OTP
* @returns A fully formed query+variables ready to be sent to GraphQL backend
*/
export function generateOtp2Query(
{
arriveBy,
banned,
date,
from,
modes,
modeSettings,
numItineraries,
preferred,
time,
to
}: OTPQueryParams,
planQuery = DefaultPlanQuery
): GraphQLQuery {
// This extracts the values from the mode settings to key value pairs
const modeSettingValues = modeSettings.reduce((prev, cur) => {
if (cur.type === "SLIDER" && cur.inverseKey) {
prev[cur.inverseKey] = cur.high - cur.value + cur.low;
}
prev[cur.key] = cur.value;
// If we assign a value on true, return the value (or null) instead of a boolean.
if (cur.type === "CHECKBOX" && cur.truthValue) {
prev[cur.key] =
cur.value === true ? cur.truthValue : cur.falseValue ?? null;
}
return prev;
}, {}) as ModeSettingValues;
const {
bikeReluctance,
carReluctance,
walkSpeed,
walkReluctance,
wheelchair
} = modeSettingValues;
return {
query: print(planQuery),
variables: {
arriveBy,
banned,
bikeReluctance,
carReluctance,
date,
fromPlace: `${from.name}::${from.lat},${from.lon}}`,
modes,
numItineraries,
preferred,
time,
toPlace: `${to.name}::${to.lat},${to.lon}}`,
walkReluctance,
walkSpeed,
wheelchair
}
};
}