Skip to content

Instantly share code, notes, and snippets.

@otaavioo
Created May 2, 2024 20:40
Show Gist options
  • Save otaavioo/e51e76e702bf3180e2b80bb2fe524566 to your computer and use it in GitHub Desktop.
Save otaavioo/e51e76e702bf3180e2b80bb2fe524566 to your computer and use it in GitHub Desktop.
Handle calls to API
class Api {
constructor(baseUrl) {
this.__setHash()
this.__setHeaders()
this.baseUrl = baseUrl
}
__setHash = () => {
this.hash = document.cookie
.split(';')
.map((cookie) => {
cookie = cookie.split('=')
return {
key: cookie[0].trim(),
value: cookie[1],
}
})
.find(cookie => cookie.key === 'Hash').value
}
__setHeaders = () => {
this.headers = new Headers()
this.headers.append('Accept', 'application/json, text/plain, */*')
this.headers.append('Hash', this.hash)
}
__exec = (url = '', params = {}) => {
return fetch(this.baseUrl + url, params)
.then(response => response.json())
}
get = (url = '', params = null) => {
if (params) {
url += '/?' + new URLSearchParams(params).toString()
}
return fetch(this.baseUrl + url, {
method: 'GET',
headers: this.headers,
})
}
post = (url = '', params = {}) => {
if (params) {
url += '/?' + new URLSearchParams(params).toString()
}
return fetch(this.baseUrl + url, {
method: 'POST',
headers: this.headers,
body: JSON.stringify(params),
})
}
put = (url = '', params = {}) => {
return this.__exec(url, {
method: 'PUT',
headers: this.headers,
body: new URLSearchParams(params),
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment