]> git.openstreetmap.org Git - nominatim-ui.git/blobdiff - src/lib/api_utils.js
catch and report JSON parsing errors, simulate API HTTP responses (#168)
[nominatim-ui.git] / src / lib / api_utils.js
index 93363e4f5ff3c45cfb465030947b888e0bd50f39..8de3f0f237e1880fa5bf539be9b09c434a105b2e 100644 (file)
@@ -1,8 +1,5 @@
-
-import { get_config_value } from './config_reader.js';
 import { last_api_request_url_store, error_store } from './stores.js';
 
-
 function api_request_progress(status) {
   var loading_el = document.getElementById('loading');
   if (!loading_el) return; // might not be on page yet
@@ -13,17 +10,43 @@ function api_request_progress(status) {
 export async function fetch_from_api(endpoint_name, params, callback) {
   var api_url = generate_nominatim_api_url(endpoint_name, params);
 
+  // For the test suite:
+  // If httpbin_status URL parameter is set we call https://httpbin.org/#/Status_codes
+  var tmp_params = new URLSearchParams(window.location.search);
+  if (tmp_params && tmp_params.get('httpbin_status')) {
+    api_url = 'https://httpbin.org/status/' + parseInt(tmp_params.get('httpbin_status'), 10);
+  }
+
   api_request_progress('start');
   if (endpoint_name !== 'status') last_api_request_url_store.set(null);
 
   try {
-    await fetch(api_url)
-      .then(response => response.json())
-      .then(data => {
-        if (data.error) {
-          error_store.set(data.error.message);
+    await fetch(api_url, { headers: Nominatim_Config.Nominatim_API_Endpoint_Headers || {} })
+      .then(async (response) => {
+        if (!((response.status >= 200 && response.status < 300) || response.status === 404)) {
+          error_store.set(`Error fetching data from ${api_url} (${response.statusText})`);
+          return undefined;
+        }
+
+        // Parse JSON here instead of returning a promise so we can catch possible
+        // errors.
+        var data;
+        try {
+          data = await response.json();
+        } catch (err) {
+          // e.g. 'JSON.parse: unexpected non-whitespace character after JSON data at line 1'
+          error_store.set(`Error parsing JSON data from ${api_url} (${err})`);
+          return undefined;
+        }
+        return data;
+      })
+      .then((data) => {
+        if (data) {
+          if (data.error) {
+            error_store.set(data.error.message);
+          }
+          callback(data);
         }
-        callback(data);
         api_request_progress('finish');
       });
   } catch (error) {
@@ -36,26 +59,43 @@ export async function fetch_from_api(endpoint_name, params, callback) {
 
 var fetch_content_cache = {};
 export async function fetch_content_into_element(url, dom_element) {
+  if (!window.location.protocol.match(/^http/)) {
+    dom_element.innerHTML = `Cannot display data from ${url} here. `
+      + 'Browser security prevents loading content from file:// URLs.';
+    return;
+  }
+
   if (fetch_content_cache[url]) {
     dom_element.innerHTML = fetch_content_cache[url];
     return;
   }
-  await fetch(url)
-    .then(response => response.text())
-    .then(html => {
-      html = html.replace('Nominatim_API_Endpoint', get_config_value('Nominatim_API_Endpoint'));
-      dom_element.innerHTML = html;
-      fetch_content_cache[url] = html;
-    });
+  try {
+    await fetch(url)
+      .then(response => response.text())
+      .then(html => {
+        html = html.replace('Nominatim_API_Endpoint', Nominatim_Config.Nominatim_API_Endpoint);
+        dom_element.innerHTML = html;
+        fetch_content_cache[url] = html;
+      });
+  } catch (error) {
+    dom_element.innerHTML = `Error fetching content from ${url} (${error})`;
+  }
 }
 
 function generate_nominatim_api_url(endpoint_name, params) {
-  return get_config_value('Nominatim_API_Endpoint') + endpoint_name + '.php?'
+  extend_parameters(params, Nominatim_Config.Nominatim_API_Endpoint_Params);
+  return Nominatim_Config.Nominatim_API_Endpoint + endpoint_name + '.php?'
          + Object.keys(clean_up_parameters(params)).map((k) => {
            return encodeURIComponent(k) + '=' + encodeURIComponent(params[k]);
          }).join('&');
 }
 
+function extend_parameters(params, params2) {
+  var param_names = Object.keys(params2);
+  for (var i = 0; i < param_names.length; i += 1) {
+    params[param_names[i]] = params2[param_names[i]];
+  }
+}
 
 function clean_up_parameters(params) {
   // `&a=&b=&c=1` => '&c=1'
@@ -70,7 +110,7 @@ function clean_up_parameters(params) {
 }
 
 export function update_html_title(title) {
-  document.title = [title, get_config_value('Page_Title')]
+  document.title = [title, Nominatim_Config.Page_Title]
     .filter((val) => val && val.length > 1)
     .join(' | ');
 }