Grupo-AFAL/frontend-helpers

View on GitHub
javascript/src/utils/google-maps-loader.js

Summary

Maintainability
A
1 hr
Test Coverage
A
91%
const API_URL = 'https://maps.googleapis.com/maps/api/js'
const CALLBACK_NAME = '__googleMapsApiOnLoadCallback'
const optionsKeys = ['channel', 'client', 'key', 'language', 'region', 'v']
 
const defaultTimeout = 10000
let promise = null
 
Function `default` has 27 lines of code (exceeds 25 allowed). Consider refactoring.
export default function (options = {}) {
promise =
promise ||
new Promise((resolve, reject) => {
// Reject the promise after a timeout
const timeoutId = setTimeout(function () {
window[CALLBACK_NAME] = function () {} // Set the on load callback to a no-op
reject(new Error('Could not load the Google Maps API'))
}, options.timeout || defaultTimeout)
 
// Hook up the on load callback
window[CALLBACK_NAME] = function () {
if (timeoutId !== null) {
clearTimeout(timeoutId)
}
resolve(window.google.maps)
}
 
// Prepare the `script` tag to be inserted into the page
const scriptElement = document.createElement('script')
const params = [`callback=${CALLBACK_NAME}`]
optionsKeys.forEach(key => {
if (options[key]) {
params.push(`${key}=${options[key]}`)
}
})
if (options.libraries && options.libraries.length) {
params.push(`libraries=${options.libraries.join(',')}`)
}
scriptElement.src = `${options.apiUrl || API_URL}?${params.join('&')}`
 
// Insert the `script` tag
document.body.appendChild(scriptElement)
})
 
return promise
}