-
Notifications
You must be signed in to change notification settings - Fork 1
/
fetch-locations.ts
75 lines (65 loc) · 2.09 KB
/
fetch-locations.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
import axios from 'axios';
import {loadAll, CORE_SCHEMA} from 'js-yaml';
import {readFileSync, writeFileSync} from 'fs';
import {Play} from './src/types';
import loc from './src/locations.json';
const locations: {[index: string]: number[]} = {...loc};
let data: Play[] = [];
try {
data = loadAll(readFileSync('./data.yaml', 'utf8'), null, {
schema: CORE_SCHEMA,
}) as Play[];
} catch (error) {
console.log(error);
}
const locationIds = data
// find plays with wikidata ID
.filter((p) => p.settings?.find((s) => s.location?.wikidataId))
// extract wikidata IDs
.map((p) =>
p.settings
?.filter((s) => s.location?.wikidataId)
.map((s) => s.location?.wikidataId)
)
.flat()
// remove duplicates
.filter((id, index, self) => self.indexOf(id) === index);
const endpoint = 'https://query.wikidata.org/sparql';
async function fetchLocations() {
const results: {[index: string]: number[]} = {};
for (let i = 0; i < locationIds.length; i++) {
const id = locationIds[i];
const loc = locations[id as string];
if (loc) {
console.log(`${id} exists`);
results[id as string] = loc;
} else {
const sparql = `SELECT ?loc WHERE { wd:${id} wdt:P625 ?loc .}`;
const url = `${endpoint}?query=${encodeURIComponent(sparql)}`;
console.log(`${id} ${url}`);
try {
const response = await axios.get(url);
if (response.status === 200) {
const loc = response.data.results?.bindings[0]?.loc.value;
let long: number, lat: number;
const m = loc.match(/\((-?[.0-9]+) (-?[.0-9]+)\)/);
if (m) {
long = parseFloat(m[1]);
lat = parseFloat(m[2]);
results[id as string] = [lat, long];
console.log(loc, long, lat);
}
} else {
console.log(response.status);
}
} catch (error) {
console.log(error);
}
console.log('waiting...');
await new Promise((r) => setTimeout(r, 1000));
}
}
console.log(results);
writeFileSync('./src/locations.json', JSON.stringify(results, null, 2));
}
fetchLocations();