Reestructura APIClient

This commit is contained in:
Juan Pablo Vial
2025-05-13 09:32:48 -04:00
parent 4e0b611bcf
commit b45d03aa7e

View File

@ -1,28 +1,32 @@
<script>
class APIClient {
static getApiKey() {
return '{{md5($API_KEY)}}{{($login->isIn()) ? $login->getSeparator() . $login->getToken() : ''}}'
}
static fetch(url, options=null, showErrors=false) {
return fetchAPI(url, options, showErrors)
if (options === null) {
options = {}
}
if (!Object.hasOwn(options, 'headers')) {
options['headers'] = {}
}
if (!Object.hasOwn(options['headers'], 'Authorization')) {
options['headers']['Authorization'] = `Bearer ${APIClient.getApiKey()}`
}
return fetch(url, options).then(response => {
if (response.ok) {
return response
}
throw new Error(JSON.stringify({code: response.status, message: response.statusText, url}))
}).catch(error => {
if (showErrors) {
console.error(error)
}
})
}
}
function fetchAPI(url, options=null, showErrors=false) {
if (options === null) {
options = {}
}
if (!Object.hasOwn(options, 'headers')) {
options['headers'] = {}
}
if (!Object.hasOwn(options['headers'], 'Authorization')) {
options['headers']['Authorization'] = 'Bearer {{md5($API_KEY)}}{{($login->isIn()) ? $login->getSeparator() . $login->getToken() : ''}}'
}
return fetch(url, options).then(response => {
if (response.ok) {
return response
}
throw new Error(JSON.stringify({code: response.status, message: response.statusText, url}))
}).catch(error => {
if (showErrors) {
console.error(error)
}
})
return APIClient.fetch(url, options, showErrors)
}
</script>