Repository navigation
Expand file tree
/
Copy pathmap-api.test.mjs
More file actions
431 lines (414 loc) · 12.3 KB
/
Copy pathmap-api.test.mjs
File metadata and controls
431 lines (414 loc) · 12.3 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
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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
import assert from "node:assert/strict";
import test from "node:test";
import { handleApiRequest } from "../server/api-router.js";
import {
buildOverpassQuery,
handleMapRequest,
mapCell,
} from "../server/map.js";
function overpassResponse(elements = []) {
return new Response(JSON.stringify({ elements }), {
status: 200,
headers: { "content-type": "application/json" },
});
}
test("builds a bounded labelled Overpass query and normalizes geometry", async () => {
const calls = [];
const response = await handleApiRequest(
new Request("https://example.test/api/map?lat=37.5563&lng=126.922"),
{},
{
cache: null,
fetchImpl: async (url, options) => {
calls.push({ url, options });
return overpassResponse([
{
type: "way",
tags: {
highway: "primary",
name: "Yanghwa-ro",
"name:ko": "양화로",
"name:en": "Yanghwa-ro",
},
geometry: [
{ lat: 37.55, lon: 126.91 },
{ lat: 37.56, lon: 126.92 },
],
},
{
type: "way",
tags: { highway: "residential" },
geometry: [
{ lat: 37.56, lon: 126.92 },
{ lat: 37.57, lon: 126.93 },
],
},
{
type: "node",
lat: 37.5572,
lon: 126.9245,
tags: {
railway: "station",
name: "Hongik University",
"name:ko": "홍대입구역",
"name:en": "Hongik University Station",
"name:ja": "弘大入口駅",
},
},
{
type: "node",
lat: 37.5568,
lon: 126.923,
tags: {
leisure: "park",
name: "경의선숲길",
},
},
]);
},
},
);
assert.equal(response.status, 200);
assert.deepEqual(await response.json(), {
cell: "37.5552,126.9216",
attribution: "© OSM CONTRIBUTORS",
roads: [
{
kind: "major",
points: [[37.55, 126.91], [37.56, 126.92]],
},
{
kind: "minor",
points: [[37.56, 126.92], [37.57, 126.93]],
},
],
labels: [
{
kind: "transit",
name: "Hongik University",
localizedNames: {
en: "Hongik University Station",
ja: "弘大入口駅",
ko: "홍대입구역",
},
point: [37.5572, 126.9245],
},
{
kind: "road",
name: "Yanghwa-ro",
localizedNames: {
ko: "양화로",
en: "Yanghwa-ro",
},
point: [37.56, 126.92],
},
{
kind: "landmark",
name: "경의선숲길",
point: [37.5568, 126.923],
},
],
});
assert.equal(calls.length, 1);
assert.equal(calls[0].url, "https://overpass-api.de/api/interpreter");
assert.equal(calls[0].options.method, "POST");
assert.equal(calls[0].options.redirect, "error");
assert.deepEqual(calls[0].options.headers, {
"content-type": "application/x-www-form-urlencoded;charset=UTF-8",
"user-agent": "SANDEVISTAN-G2-Personal-Prototype/0.1",
});
const query = calls[0].options.body.get("data");
assert.match(query, /way\["highway"\]\(around:650,37\.5563,126\.922\)/);
assert.match(
query,
/nwr\["name"\]\[~"\^\(railway\|public_transport\|place\|leisure\|tourism\|amenity\)\$"~"\^\(station\|halt\|city\|town\|village\|suburb\|quarter\|neighbourhood\|locality\|square\|park\|garden\|stadium\|museum\|attraction\|gallery\|hospital\|university\|school\|library\|marketplace\|townhall\)\$"\]/,
);
assert.match(query, /\.roads out geom;\.named out center;$/);
assert.ok(calls[0].options.signal instanceof AbortSignal);
assert.equal(
response.headers.get("cache-control"),
"public, max-age=3600, s-maxage=86400",
);
});
test("sanitizes, prioritizes, deduplicates, and caps labels", async () => {
const minorDuplicate = {
type: "way",
tags: { highway: "residential", name: "main road" },
geometry: [
{ lat: 37.5, lon: 127 },
{ lat: 37.501, lon: 127.001 },
],
};
const landmark = {
type: "node",
lat: 37.502,
lon: 127.002,
tags: { leisure: "park", name: " 시민\u0000 공원\n" },
};
const place = {
type: "node",
lat: 37.503,
lon: 127.003,
tags: { place: "neighbourhood", name: "연남동" },
};
const transit = {
type: "node",
lat: 37.504,
lon: 127.004,
tags: {
public_transport: "station",
name: "Hongdae",
"name:ko": "홍대입구역",
},
};
const majorDuplicate = {
type: "way",
tags: { highway: "primary", name: "MAIN ROAD" },
geometry: [
{ lat: 37.505, lon: 127.005 },
{ lat: 37.506, lon: 127.006 },
{ lat: 37.507, lon: 127.007 },
],
};
const longPlace = {
type: "node",
lat: 37.508,
lon: 127.008,
tags: { place: "locality", name: "가".repeat(45) },
};
const invalid = {
type: "node",
lat: 91,
lon: 127,
tags: { railway: "station", name: "INVALID" },
};
const extras = Array.from({ length: 30 }, (_, index) => ({
type: "way",
tags: { highway: "service", name: `도로 ${index}` },
geometry: [
{ lat: 37.51 + index / 10_000, lon: 127 },
{ lat: 37.51 + index / 10_000, lon: 127.001 },
],
}));
const response = await handleMapRequest(
new Request("https://example.test/api/map?lat=37.5&lng=127"),
{},
{
cache: null,
fetchImpl: async () => overpassResponse([
minorDuplicate,
landmark,
place,
transit,
majorDuplicate,
longPlace,
invalid,
...extras,
]),
},
);
const { labels } = await response.json();
assert.equal(labels.length, 24);
assert.deepEqual(labels.slice(0, 5).map(({ kind }) => kind), [
"transit",
"place",
"place",
"road",
"landmark",
]);
assert.equal(labels[0].name, "Hongdae");
assert.equal(labels[0].localizedNames.ko, "홍대입구역");
assert.equal(labels.find(({ name }) => name.startsWith("가")).name, "가".repeat(40));
assert.equal(labels.find(({ kind }) => kind === "landmark").name, "시민 공원");
const duplicates = labels.filter(
({ name }) => name.toLowerCase() === "main road",
);
assert.deepEqual(duplicates, [{
kind: "road",
name: "MAIN ROAD",
point: [37.506, 127.006],
}]);
assert.equal(labels.some(({ name }) => name === "INVALID"), false);
});
test("keeps only eight valid bounded OSM language names per label", async () => {
const languages = ["aa", "ab", "ae", "af", "ak", "am", "an", "ar", "as"];
const localizedTags = Object.fromEntries(
languages.map((language, index) => [
`name:${language}`,
index === 0 ? " Name\u0000 zero " : `Name ${index}`,
]),
);
const response = await handleMapRequest(
new Request("https://example.test/api/map?lat=35.6812&lng=139.7671"),
{},
{
cache: null,
fetchImpl: async () => overpassResponse([{
type: "node",
lat: 35.6812,
lon: 139.7671,
tags: {
railway: "station",
name: "Tokyo Station",
...localizedTags,
"name:bad tag": "Invalid",
},
}]),
},
);
const { labels } = await response.json();
assert.deepEqual(Object.keys(labels[0].localizedNames), languages.slice(0, 8));
assert.equal(labels[0].localizedNames.aa, "Name zero");
assert.equal(labels[0].localizedNames["bad tag"], undefined);
});
test("validates coordinates before contacting Overpass", async () => {
for (const query of [
"lat=91&lng=126.922",
"lat=x&lng=126.922",
"lat=&lng=126.922",
"lat=37.5&lng=181",
]) {
let calls = 0;
const response = await handleMapRequest(
new Request(`https://example.test/api/map?${query}`),
{},
{
fetchImpl: async () => {
calls += 1;
return overpassResponse();
},
},
);
assert.equal(response.status, 400);
assert.equal((await response.json()).error.code, "INVALID_COORDINATE");
assert.equal(calls, 0);
}
});
test("leaves non-GET map requests to the API 404", async () => {
const response = await handleApiRequest(
new Request("https://example.test/api/map?lat=37.5&lng=127", {
method: "POST",
}),
{},
);
assert.equal(response.status, 404);
assert.equal((await response.json()).error.code, "API_NOT_FOUND");
});
test("prefers major roads and enforces way and point limits", async () => {
const minor = Array.from({ length: 180 }, (_, index) => ({
type: "way",
tags: { highway: "service" },
geometry: [
{ lat: 37 + index / 10_000, lon: 127 },
{ lat: 37 + index / 10_000, lon: 127.001 },
],
}));
const major = {
type: "way",
tags: { highway: "secondary" },
geometry: Array.from({ length: 3_900 }, (_, index) => ({
lat: 37 + index / 1_000_000,
lon: 127,
})),
};
const response = await handleMapRequest(
new Request("https://example.test/api/map?lat=37.5&lng=127"),
{},
{
cache: null,
fetchImpl: async () => overpassResponse([...minor, major]),
},
);
const body = await response.json();
assert.equal(body.roads[0].kind, "major");
assert.ok(body.roads.length <= 180);
assert.ok(
body.roads.reduce((sum, road) => sum + road.points.length, 0) <= 4_000,
);
});
test("caches a normalized response by rounded location cell", async () => {
const entries = new Map();
const cacheKeys = [];
const cache = {
async match(request) {
cacheKeys.push(request.url);
return entries.get(request.url)?.clone();
},
async put(request, response) {
entries.set(request.url, response.clone());
},
};
let calls = 0;
const dependencies = {
cache,
fetchImpl: async () => {
calls += 1;
return overpassResponse();
},
};
const first = await handleMapRequest(
new Request("https://example.test/api/map?lat=37.5563&lng=126.922"),
{},
dependencies,
);
const second = await handleMapRequest(
new Request("https://example.test/api/map?lat=37.5568&lng=126.923"),
{},
dependencies,
);
assert.equal(first.status, 200);
assert.equal(second.status, 200);
assert.equal(calls, 1);
assert.equal(new Set(cacheKeys).size, 1);
assert.match(cacheKeys[0], /roads-labels-v5/);
});
test("maps upstream, size, and timeout failures to stable errors", async () => {
const upstream = await handleMapRequest(
new Request("https://example.test/api/map?lat=37.5&lng=127"),
{},
{
cache: null,
fetchImpl: async () => new Response("bad", { status: 503 }),
},
);
assert.equal(upstream.status, 502);
assert.equal((await upstream.json()).error.code, "MAP_UPSTREAM_ERROR");
const tooLarge = await handleMapRequest(
new Request("https://example.test/api/map?lat=37.5&lng=127"),
{},
{
cache: null,
fetchImpl: async () => new Response("x".repeat(1_000_001)),
},
);
assert.equal(tooLarge.status, 502);
assert.equal((await tooLarge.json()).error.code, "MAP_TOO_LARGE");
const cleared = [];
const timeout = await handleMapRequest(
new Request("https://example.test/api/map?lat=37.5&lng=127"),
{},
{
cache: null,
setTimeoutImpl: (callback, milliseconds) => {
assert.equal(milliseconds, 8_000);
callback();
return 77;
},
clearTimeoutImpl: (timer) => cleared.push(timer),
fetchImpl: async (_url, { signal }) => {
assert.equal(signal.aborted, true);
throw new DOMException("Aborted", "AbortError");
},
},
);
assert.equal(timeout.status, 504);
assert.equal((await timeout.json()).error.code, "MAP_TIMEOUT");
assert.deepEqual(cleared, [77]);
});
test("cell and query helpers are deterministic", () => {
assert.equal(mapCell(37.5563, 126.922), "37.5552,126.9216");
assert.equal(
buildOverpassQuery(37.5563, 126.922),
'[out:json][timeout:8];way["highway"](around:650,37.5563,126.922)->.roads;nwr["name"][~"^(railway|public_transport|place|leisure|tourism|amenity)$"~"^(station|halt|city|town|village|suburb|quarter|neighbourhood|locality|square|park|garden|stadium|museum|attraction|gallery|hospital|university|school|library|marketplace|townhall)$"](around:650,37.5563,126.922)->.named;.roads out geom;.named out center;',
);
});