File/loadJSON.js

import loadLocalFile from './loadLocalFile'

/**
 * Loads a JSON file. and parses it Decides to use node or fetch based on platform.
 * If using nwjs it will use node else it falls back to fetch()
 *
 * @function loadJSON
 * @async
 * @since 1.0.0
 * @memberof module:File
 * @see {@link module:File.loadLocalFile|loadLocalFile}
 *
 * @param {any} path - The path to the JSON file.
 *
 * @returns {promise} promise - A promise that resolves the parsed JSON
 * @example
 * import {loadJSON} from 'fenix-tools'
 *
 * loadJSON('./data/highscores.json')
 * .then(data => {
 *   // success for parsing and loading JSON file
 *   console.log(data)  // => A parsed JSON object.
 * })
 *
 */
export default function loadJSON (path) {
  if (window.Utils.isNwjs()) {
    return new Promise((resolve, reject) => {
      loadLocalFile(`${path}`)
        .catch(err => reject(err))
        .then(response => resolve(JSON.parse(response)))
    })
  } else {
    return new Promise((resolve, reject) => {
      window.fetch(`${path}`)
        .then((response) => resolve(response.json()))
        .catch(err => reject(err))
    })
  }
}