]> git.openstreetmap.org Git - nominatim-ui.git/blob - src/lib/api_utils.js
version 3.0.0
[nominatim-ui.git] / src / lib / api_utils.js
1 import { last_api_request_url_store, error_store } from './stores.js';
2
3 function api_request_progress(status) {
4   var loading_el = document.getElementById('loading');
5   if (!loading_el) return; // might not be on page yet
6
7   loading_el.style.display = (status === 'start') ? 'block' : null;
8 }
9
10 export async function fetch_from_api(endpoint_name, params, callback) {
11   var api_url = generate_nominatim_api_url(endpoint_name, params);
12
13   api_request_progress('start');
14   if (endpoint_name !== 'status') last_api_request_url_store.set(null);
15
16   try {
17     await fetch(api_url)
18       .then(response => response.json())
19       .then(data => {
20         if (data.error) {
21           error_store.set(data.error.message);
22         }
23         callback(data);
24         api_request_progress('finish');
25       });
26   } catch (error) {
27     error_store.set(`Error fetching data from ${api_url} (${error})`);
28     api_request_progress('finish');
29   }
30
31   if (endpoint_name !== 'status') last_api_request_url_store.set(api_url);
32 }
33
34 var fetch_content_cache = {};
35 export async function fetch_content_into_element(url, dom_element) {
36   if (fetch_content_cache[url]) {
37     dom_element.innerHTML = fetch_content_cache[url];
38     return;
39   }
40   await fetch(url)
41     .then(response => response.text())
42     .then(html => {
43       html = html.replace('Nominatim_API_Endpoint', Nominatim_Config.Nominatim_API_Endpoint);
44       dom_element.innerHTML = html;
45       fetch_content_cache[url] = html;
46     });
47 }
48
49 function generate_nominatim_api_url(endpoint_name, params) {
50   return Nominatim_Config.Nominatim_API_Endpoint + endpoint_name + '.php?'
51          + Object.keys(clean_up_parameters(params)).map((k) => {
52            return encodeURIComponent(k) + '=' + encodeURIComponent(params[k]);
53          }).join('&');
54 }
55
56
57 function clean_up_parameters(params) {
58   // `&a=&b=&c=1` => '&c=1'
59   var param_names = Object.keys(params);
60   for (var i = 0; i < param_names.length; i += 1) {
61     var val = params[param_names[i]];
62     if (typeof (val) === 'undefined' || val === '' || val === null) {
63       delete params[param_names[i]];
64     }
65   }
66   return params;
67 }
68
69 export function update_html_title(title) {
70   document.title = [title, Nominatim_Config.Page_Title]
71     .filter((val) => val && val.length > 1)
72     .join(' | ');
73 }
74