Skip to content

Instantly share code, notes, and snippets.

@adrian-afergon
Created May 15, 2023 07:58
Show Gist options
  • Save adrian-afergon/36df94bba788bc7a58b3e562b9810620 to your computer and use it in GitHub Desktop.
Save adrian-afergon/36df94bba788bc7a58b3e562b9810620 to your computer and use it in GitHub Desktop.
type Headers = { [key: string]: string }
const baseUrl = process.env.BASE_URL || ''
const get = async <T>(url: string, headers?: Headers) => {
const response = await fetch(`${baseUrl}${url}`, {
method: 'GET',
headers: {...headers}
})
return await response.json() as T
}
const post = async <T, K>(url: string, body: K, headers?: Headers) => {
const response = await fetch(`${baseUrl}${url}`, {
method: 'POST',
headers: {
...headers,
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(body)
})
return await response.json() as T
}
const put = async <T, K>(url: string, body: K, headers?: Headers) => {
const response = await fetch(`${baseUrl}${url}`, {
method: 'PUT',
headers: {
...headers,
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(body)
})
return await response.json() as T
}
const _delete = async <T>(url: string, headers?: Headers) => {
const response = await fetch(`${baseUrl}${url}`, {
method: 'DELETE',
headers: {...headers}
})
return await response.json() as T
}
export const http = {
get,
post,
put,
delete: _delete
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment