Api en archivo separado
This commit is contained in:
28
app/resources/views/layout/body/scripts/api.blade.php
Normal file
28
app/resources/views/layout/body/scripts/api.blade.php
Normal file
@ -0,0 +1,28 @@
|
||||
<script>
|
||||
class APIClient {
|
||||
static fetch(url, options=null, showErrors=false) {
|
||||
return fetchAPI(url, options, showErrors)
|
||||
}
|
||||
}
|
||||
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)
|
||||
}
|
||||
})
|
||||
}
|
||||
</script>
|
Reference in New Issue
Block a user